Home >Web Front-end >JS Tutorial >An in-depth anatomy of how Ajax works

An in-depth anatomy of how Ajax works

零到壹度
零到壹度Original
2018-04-03 11:11:011518browse

This article mainly introduces the in-depth dissection of the working principle of Ajax. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

1. Background of ajax technology

It is undeniable that the popularity of ajax technology benefits from Google’s vigorous promotion. It is precisely because of the extensive application of Ajax technology such as Google Earth, Google Suggest and Gmail that the popularity of Ajax was born. This also makes Microsoft feel extremely embarrassed, because as early as 1997, Microsoft had invented the key technology in ajax, and when IE5 was launched in 1999, it began to support the XmlHttpRequest object, and Microsoft had already started to use it before. Ajax is used in some products, such as some applications in the MSDN website menu. Unfortunately, for some unknown reason, after Microsoft invented the core technology of ajax, it did not see its potential and develop and promote it, but shelved it. I personally find this very strange, because with Microsoft's resources and strategic vision, it should not be unable to see the prospects of ajax technology. The only explanation may be that its main competitor at the time The disappearance of Netscape has made it paralyzed and slow. After all, giants also take naps, such as IBM's strategic mistakes against Microsoft. It was this mistake that made its current competitor Google's leading position in Ajax. In fact, Google's current leadership in Ajax technology is beyond the reach of Microsoft. This will be discussed later when I talk about the flaws of Ajax. will also be mentioned. Now Microsoft is also aware of this problem, so it has also begun to catch up in the ajax field. For example, it launched its own ajax framework atlas, and also provided an interface for implementing asynchronous callbacks in .NET 2.0, namely the ICallBack interface. . So why is Microsoft so nervous about its lagging behind in ajax? Now let us analyze the profound meaning behind ajax technology.

2. The significance of ajax technology

We are more or less exposed to or applied to ajax in our daily development. When it comes to the significance of ajax technology, we pay attention to The most important thing is undoubtedly to improve the user experience. However, if we combine the future development trends of computers and the Internet, we will find that ajax technology represents this trend in some aspects. Why do you say this way? We know that since the advent of computers, desktop software has always occupied an absolutely dominant position, but the emergence and success of the Internet has caused subtle changes in all this. A considerable number of people believe that sooner or later, data and computer software will move from the desktop to the Internet. In other words, computers in the future may abandon bulky hard drives and obtain data and services directly from the Internet. I remember when I was in college, a professor once imagined such a scenario when he was giving us a class. Maybe In the future, there will be no redundant software and programs on the computer desktop, but only one IE. Although it seems that we are still far away from this day, and there are still many problems that need to be solved, I think this is not a dream. , but a reality that will be realized sooner or later. Well, the main problem is that the Internet connection is unstable. No one wants to watch their computer download data from the server bit by bit. So, does ajax solve this problem? To be honest, it is not so much ajax. Rather than solving the problem, it just masks the problem. It just acts as a buffer between the server and the client, tricking users into thinking there is no interruption in service. To be precise, ajax does not increase the speed of downloading data from the server, but just makes the wait less frustrating. But just this was enough to have a huge impact and shock, and it actually had a huge impact on desktop software. I will use an example to illustrate this point. We can compare Outlook Express and Gmail. The former is a typical desktop software, and the latter is a B/S mode implemented by ajax. In fact, the latter is slowly replacing the former. Gmail has almost the same functionality as Outlook Express when sending and receiving emails, and it does not require the installation of a client program. This is one of the main reasons why Microsoft is so afraid of the impact of Ajax, and in a survey it conducted not long ago, it regarded Google as their main competitor in the next ten years. Of course, this change will not eliminate all desktop software. None of the existing browsers can handle complex images like desktop programs such as PhotoShop. But we cannot ignore its influence and impact.

3. About the name of ajax

The full name of ajax is Asynchronous JavaScript and XML. Among them, Asynchronous means asynchronous, which is different from the one used in traditional web development. synchronized way.

4. About synchronization and asynchronous

Asynchronous transmission is character-oriented transmission, and its unit is character; while synchronous transmission is bit-oriented transmission, and its unit is frame, When it is transmitted, the clocks of the receiver and the sender are required to be consistent.

Specifically, asynchronous transmission divides bits into small groups for transmission. Generally, each group is an 8-bit character. There is a start bit and a stop bit at the head and tail of each group. During the transmission process, the clocks of the receiver and the sender do not need to be consistent. That is to say, the sending The party can send these groups at any time without the receiving party knowing when it will arrive. One of the most obvious examples is the communication between the computer keyboard and the host. When a key is pressed, an 8-bit ASCII code is sent to the host. The keyboard can send the code at any time, depending on the user's input speed. The internal hardware must Ability to receive a typed character at any time. This is a typical asynchronous transmission process. A potential problem with asynchronous transmission is that the receiver does not know when the data will arrive. Before it detects the data and responds, the first bit has passed. It's like someone unexpectedly comes up from behind and talks to you, and you don't have time to react and miss the first few words. Therefore, each asynchronous transmission of information begins with a start bit, which notifies the receiver that the data has arrived, which gives the receiver time to respond, receive and cache the data bits; at the end of the transmission, a stop bit indicates Termination of this transmission of information. By convention, an idle (not transmitting data) line actually carries a signal representing a binary 1. The start bit of the step transmission causes the signal to become 0, and the other bits cause the signal to change with the transmitted data information. Finally, the stop bit changes the signal back to 1, where it remains until the next start bit arrives. For example, the number "1" on the keyboard will send "00110001" according to the 8-bit extended ASCII encoding. At the same time, a start bit needs to be added in front of the 8-bit bit and a stop bit will follow.

The bit packets transmitted simultaneously are much larger. Instead of sending each character independently, each with its own start bit and stop bit, it combines them and sends them together. We call these combinations data frames, or simply frames.

The first part of the data frame contains a set of synchronization characters, which is a unique combination of bits, similar to the start bit mentioned earlier, used to notify the receiver that a frame has arrived, but it can also Ensure that the sampling speed of the receiver is consistent with the arrival speed of bits, so that the sending and receiving parties are synchronized.

The last part of the frame is an end-of-frame marker. Like the synchronization character, it is also a unique bit string, similar to the stop bit mentioned earlier, used to indicate that there is no other upcoming data before the next frame begins.

Synchronous transmission is usually much faster than asynchronous transmission. The receiver does not have to start and stop each character. Once the frame synchronization characters are detected, it receives them as the next data arrives. In addition, the overhead of synchronous transmission is also relatively small. For example, a typical frame may have 500 bytes (i.e. 4000 bits) of data, which may only contain 100 bits of overhead. At this time, the added bits increase the total number of transmitted bits by 2.5%, which is much smaller than the 25% increase in asynchronous transmission. As the number of actual data bits in the data frame increases, the percentage of overhead bits decreases accordingly. However, the longer the data bits, the larger the buffer required to cache the data, which limits the size of a frame. In addition, the larger the frame, the longer the continuous time it occupies the transmission medium. In extreme cases, this will cause other users to wait too long.

After understanding the concepts of synchronization and asynchronousness, it should be clearer why ajax can improve the user experience. It uses asynchronous request methods. For example, if the community where your home is located is facing a water cutoff due to some circumstances, the relevant departments have announced two plans. One is to completely cut off the water supply for 8 hours; Return to normal after hours. The second is to not completely cut off the water for 10 hours. During these 10 hours, the water is not completely cut off, but the flow rate is much smaller than before. After 10 hours, the normal flow rate will be restored. So, which method would you choose if it were you? ? Apparently it's the latter.

5. The technology included in ajax

Everyone knows that ajax is not a new technology, but a combination of several original technologies. It is composed of the following technologies.

1. Use CSS and XHTML to express.

2. Use DOM model for interaction and dynamic display.

3. Use XMLHttpRequest to communicate asynchronously with the server.

4. Use javascript to bind and call.

Among the above technologies, except for the XmlHttpRequest object, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C, it is already a A de facto standard as almost all major browsers currently support it.

6. Ajax principle and XmlHttpRequest object

The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object, obtain the data from the server, and then use javascript to Manipulate the DOM to update the page. The most critical step in this is to obtain the request data from the server. To understand this process and principle, we must understand something about XMLHttpRequest.

XMLHttpRequest is the core mechanism of ajax. It was first introduced in IE5 and is a technology that supports asynchronous requests. To put it simply, JavaScript can make requests to the server and process responses in a timely manner without blocking the user. Achieve no refresh effect.

So let’s start with XMLHttpRequest and see how it works.

First, let’s take a look at the properties of the XMLHttpRequest object.

Its attributes are:

    1. onreadystatechange The event handler for the event triggered each time the state changes.

    2. responseText The string form of data returned from the server process.

    3. responseXML DOM-compatible document data object returned from the server process.

    4. status Numeric code returned from the server, such as the common 404 (not found) and 200 (ready)

    5. status Text accompanying status Code string information

    6. readyState Object status value

0 (uninitialized) The object has been created, but has not been initialized (not yet Call the open method)
1 (Initialization) The object has been created, but the send method has not been called yet
2 (Sending data) The send method has been called, but the current status and http header are unknown
3 (Data is being transmitted) Already Receive part of the data. Because the response and http header are incomplete, an error will occur when obtaining part of the data through responseBody and responseText.

 4 (Complete) The data is received. At this time, it can be obtained through responseXml and responseText. Complete response data

However, due to differences between browsers, creating an XMLHttpRequest object may require different methods. This difference is mainly reflected between IE and other browsers. The following is a relatively standard method of creating an XMLHttpRequest object.

function CreateXmlHttp() {

    //非IE浏览器创建XmlHttpRequest对象
    if (window.XmlHttpRequest) {
        xmlhttp = new XmlHttpRequest();
    }

    //IE浏览器创建XmlHttpRequest对象
    if (window.ActiveXObject) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
            try {
                xmlhttp = new ActiveXObject("msxml2.XMLHTTP");
            }
            catch (ex) { }
        }
    }
}

function Ustbwuyi() {

    var data = document.getElementById("username").value;
    CreateXmlHttp();
    if (!xmlhttp) {
        alert("创建xmlhttp对象异常!");
        return false;
    }

    xmlhttp.open("POST", url, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            document.getElementById("user1").innerHTML = "数据正在加载...";
            if (xmlhttp.status == 200) {
                document.write(xmlhttp.responseText);
            }
        }
    }
    xmlhttp.send();
}

As shown above, the function first checks the overall status of XMLHttpRequest and ensures that it has been completed (readyStatus=4), that is, the data has been sent. Then query the request status according to the server's settings. If everything is ready (status=200), then perform the following required operations.

For the two methods of XmlHttpRequest, open and send, the open method specifies:

a. The type of data submitted to the server, that is, post or get.

b, requested url address and passed parameters.

c. Transmission mode, false means synchronous, true means asynchronous. Defaults to true. If it is an asynchronous communication mode (true), the client does not wait for the server's response; if it is a synchronous mode (false), the client has to wait until the server returns a message before performing other operations. We need to specify the synchronization method according to actual needs. In some pages, multiple requests may be issued, or even large-scale, high-intensity requests that are organized, planned, and formed, and the latter one will overwrite the previous one. This Of course, you must specify the synchronization method.

The Send method is used to send requests.

Knowing the workflow of XMLHttpRequest, we can see that XMLHttpRequest is completely used to issue a request to the server, and its role is limited to this, but its role is the key to the entire ajax implementation, because Ajax is nothing more than two processes, making a request and responding to the request. And it's entirely a client-side technology. XMLHttpRequest handles the communication problem between the server and the client, which is why it is so important.

Now, we can probably have an understanding of the principle of ajax. We can think of the server as a data interface, which returns a plain text stream. Of course, this text stream can be in XML format, Html, Javascript code, or just a string. At this time, XMLHttpRequest requests this page from the server, and the server writes the text result into the page. This is the same as the ordinary web development process. The difference is that after the client obtains the result asynchronously, it is not directly displayed on the page. , but is processed by javascript first and then displayed on the page. As for many popular ajax controls now, such as magicajax, etc., they can return other data types such as DataSet. They just encapsulate the result of this process. In essence, there is not much difference between them.

7. Advantages of ajax

Everyone basically has a deep understanding of the benefits that Ajax brings to us. Here I will just briefly talk about a few points:

1. The biggest point is that the page does not refresh and communicates with the server within the page, giving the user a very good experience.

2. Use asynchronous mode to communicate with the server, without interrupting the user's operation, and have a faster response capability.

3. Some of the work previously burdened by the server can be transferred to the client, using the idle capacity of the client to process it, reducing the burden on the server and bandwidth, and saving space and broadband rental costs. And to reduce the burden on the server, the principle of ajax is to "fetch data on demand", which can minimize the burden on the server caused by redundant requests and responses.

4. Based on standardized and widely supported technology, there is no need to download plug-ins or small programs.

8. Disadvantages of ajax

Now I will focus on the shortcomings of ajax, because usually we mostly pay attention to the benefits that ajax brings to us, such as Improvement of user experience. The shortcomings caused by ajax have been ignored.

The defects of ajax described below are all caused by its innateness.

1. Ajax kills the back button, which destroys the browser's back mechanism. The back button is an important feature of a standard web site, but it doesn't work well with JavaScript. This is a serious problem caused by ajax, because users often hope to cancel the previous operation by going back. So is there any solution to this problem? The answer is yes. Those who have used Gmail know that the ajax technology used under Gmail solves this problem. You can go back under Gmail. However, it does not change the ajax mechanism. It just uses a stupid but effective one. The way to do this is by creating or using a hidden IFRAME to reproduce the changes on the page when the user clicks the back button to access the history. (For example, when the user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search results onto the Ajax element to restore the application state to what it was at that time.)

However, although this problem can be solved, the development cost it brings is very high, which is contrary to the rapid development required by the ajax framework. This is a very serious problem caused by ajax.

2. Security issues

Technology also brings new security threats to IT companies. Ajax technology is like establishing a direct channel for corporate data. This allows developers to inadvertently expose more data and server logic than before. Ajax logic can be hidden from client-side security scanning technology, allowing hackers to create new attacks from remote servers. Ajax is also difficult to avoid some known security weaknesses, such as cross-site scripting attacks, SQL injection attacks and credentials-based security vulnerabilities.

3. The support for search engines is relatively weak.

4. Destroyed the exception mechanism of the program. At least from the current perspective, ajax frameworks such as ajax.dll and ajaxpro.dll will destroy the exception mechanism of the program. Regarding this problem, I have encountered it during the development process, but after checking, there is almost no relevant introduction on the Internet. Later, I did an experiment myself, using ajax and traditional form submission modes to delete a piece of data... which brought great difficulties to our debugging.

5. In addition, there are some other problems, such as violating the original intention of URL and resource positioning. For example, if I give you a URL address, if Ajax technology is used, maybe what you see under the URL address is different from what I see under this URL address. This is contrary to the original intention of resource positioning.

6. Some handheld devices (such as mobile phones, PDAs, etc.) currently do not support ajax very well. For example, when we open a website using ajax technology on the mobile browser, it currently does not support it. Of course, This issue has nothing to do with us.

9. Several ajax frameworks

At present, the ajax frameworks we use mainly include ajax.dll, ajaxpro.dll, magicajax.dll and Microsoft's atlas framework. There is not much difference between the two frameworks Ajax.dll and Ajaxpro.dll, but magicajax.dll is just more powerful in encapsulation. For example, it can directly return the DataSet data set. As we have said before, ajax returns all strings. magicajax just encapsulates it. But this feature of it can bring us great convenience. For example, if our page has a list, and the data in the list is constantly changing, then we can use magicajax to process it. The operation is very simple. After adding magicajax, we will The updated list control is placed within the magicajax control, and then the update interval is defined in the pageload. The principle of atlas is similar to that of magicajax. However, one thing that needs attention is that these frameworks only support IE and do not deal with browser compatibility. You can know this by looking at their code with a decompilation tool.

In addition to these frameworks, the most commonly used method is to create xmlHttpRequest objects ourselves. This method is more flexible than the previous frameworks. In addition, I would also like to mention here the asynchronous callback interface that comes with aspnet2.0. Like ajax, it can also achieve local non-refresh, but its implementation is actually based on the xmlhttprequest object. In addition, it only supports IE. Of course, this is A competitive strategy of Microsoft.

10. Ajax example

Verify whether the user name is registered.

Use two methods

 1 ajax.dll

 2 Write the xmlhttprequest object yourself

10. Some common errors in ajax

1 Configuration problem

When configuring the page in pageload

11. The front-end part is called in the background call method...

The above is the detailed content of An in-depth anatomy of how Ajax works. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn