Home  >  Article  >  Web Front-end  >  Do you know how ajax works? Introduction to ajax and detailed summary of its principles (classic)

Do you know how ajax works? Introduction to ajax and detailed summary of its principles (classic)

寻∝梦
寻∝梦Original
2018-09-10 14:09:56930browse

This article mainly introduces an introduction to ajax, as well as some application principles of ajax, etc. Now let us read this article together

AjaxWorkingPrinciple

Before writing this article, I once wrote an essay about AJAX technology, but the aspects involved were very narrow, including the background, principles, advantages and disadvantages of AJAX technology, etc. Null is rarely involved in all aspects. The background of writing this article is that the company needs to provide training for internal programmers. The project manager found me and asked me about the training topic. Considering that Javascript, CSS and other WEB development technologies have been explained before, I decided to do a more systematic training on AJAX, so this article is actually a Training materials.

In this article, I will systematically explain AJAX technology from 10 aspects.

1. Background of ajax technology

It is undeniable that the popularity of ajax technology has benefited from the vigorous promotion of google, precisely because of google earth, google suggest and gmail, etc. The widespread application of ajax technology has given rise to the popularity of ajax. 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 have all been exposed to or applied ajax to some extent in our daily development. When it comes to the significance of ajax technology, what we pay most attention to is undoubtedly improving 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 or 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 bit by bit from the server. 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 improve 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 synchronous and asynchronous

Asynchronous transmission is a character-oriented transmission, and its unit is a character; while synchronous transmission is a bit-oriented transmission, and its unit is Yes, it requires that the clocks of the receiver and the sender are consistent when transmitting.

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 also ensures that the receiver The sampling speed 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 properties are:

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

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

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

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

status Text String information accompanying the status code

readyState Object status value

  0 (Uninitialized) The object has been created, but it has not been initialized (the open method has not been called yet)

  1 (Initialized) The object has been created, but the send method has not been called yet

  2 (Send data) The send method has been called, but the current status and http header are unknown

  3 (Data is being transmitted) Part of the data has been received because the response and http header are incomplete. At this time, it is obtained through responseBody and responseText There will be errors in some data,

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

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. Default is 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. You can transfer some of the work previously burdened by the server to the client, using the client's idle capacity 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. (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)

2. Security issues

technology also brings new challenges to IT companies Security threats, Ajax technology is like establishing a direct channel to 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 a mobile phone 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.

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

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

That’s it for this article It’s over (if you want to see more, go to the PHP Chinese website AJAX User Manual column to learn). If you have any questions, you can leave a message below.

The above is the detailed content of Do you know how ajax works? Introduction to ajax and detailed summary of its principles (classic). 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