How does Ajax work, you know? A detailed summary of the introduction and principles of Ajax (Classic)

Source: Internet
Author: User
Tags sql injection
This article mainly introduces the introduction of Ajax, as well as some of the application of Ajax principles, etc. now let's look at this article together

How Ajax Works

Before writing this article, once wrote an essay on Ajax technology, but the aspect is very narrow, on the background of Ajax technology, principles, advantages and disadvantages of the various aspects are rarely involved in null. This article was written in the background because the company needed to do a training for internal programmers. The project manager found me and asked for the subject of my training, considering that the previous Web development techniques such as JavaScript and CSS had been explained, so I decided to do a more systematic training for Ajax, so this article is actually a training material.

In this article, I will explain the Ajax technology in 10 ways.

1, the background of Ajax technology

Admittedly, the popularity of Ajax technology benefits from Google's strong promotion, it is because of Google Earth, Google suggest and Gmail, and other Ajax technology widely used, the emergence of the popularity of Ajax. This is also embarrassing for Microsoft, as early as 97, Microsoft has invented the key technology in Ajax, and in 99 when IE5 launched, it began to support the XMLHttpRequest object, and Microsoft has begun to apply Ajax in some of its products, For example, some apps in the MSDN Web site menu. Unfortunately, I do not know what the idea was, when Microsoft invented the core technology of Ajax, and did not see its potential to develop and promote, but put it aside. For this, I personally feel very strange, because Microsoft's resources and its strategic vision, should not see the future of Ajax technology, the only explanation may be because its main competitor Netscape the disappearance of it has become paralyzed and dull, after all, the Giants also have a nap time , such as IBM's past mistakes in Microsoft's strategy. It was this mistake that made its current competitor Google's leading position in Ajax, and the fact that Google's current lead in Ajax technology was beyond Microsoft's reach was mentioned later when I spoke about Ajax flaws. Now Microsoft is aware of the problem, so it's also starting to catch up in the Ajax world, like introducing its own AJAX framework, Atlas, and in. NET2.0 also provides an interface for implementing asynchronous callbacks, the Icallback interface. So why is Microsoft so nervous about its backwardness in Ajax? Now let's analyze the deep meaning behind Ajax technology.

2, the meaning of Ajax technology

We are in the normal development of a little touch or application to Ajax, talking about the meaning of Ajax technology, we have the most attention is undoubtedly to enhance the user experience. However, if we combine the trends in the future of computers and the Internet, we will find that Ajax technology represents this trend in some ways. Why do you say that? We know that since the advent of computers, the desktop software has been the absolute dominant position, but the advent and success of the Internet has begun to make a subtle change. A considerable part of the people believe that sooner or later, data and computer software will be transferred from the desktop to the Internet. In other words, the future computer may abandon the bulky hard disk, and directly from the Internet to  and services, I remember when I went to college, a professor gave us a lesson, had imagined such a scenario, perhaps in the future computer desktop, there is no unnecessary software and programs, but only one ie, Although it seems that we are far from this day, and there are a lot of problems to be solved, but I think this is not a dream, but the reality will come true sooner or later. So, the main problem is that the Internet is not stable connection, who is not willing to look at their computers from the server bit by bit of the download data, then, Ajax is not solve the problem, to tell the truth, rather than Ajax solves this problem, it is not so much as it just cover up the problem, It just acts as a buffer between the server and the client, letting the user mistakenly assume that the service is not interrupted. To be precise, Ajax does not improve the speed of downloading data from the server side, but only makes this wait less frustrating. But this is enough to have a huge impact and shock, and it actually has a huge impact on desktop software. This I use an example to illustrate, we can compare the Outlook Express and Gmail, the former is a typical desktop software, the latter is implemented by Ajax B/S mode, in fact, the latter is now slowly replacing the former, Gmail has made almost no difference to the functionality of Outlook Express when sending and receiving mail, and it doesn't need to install a client program. That is why Microsoft is so fearful of the impact of Ajax and, in its recent investigations, sees Google as one of the main reasons for its major rivals in the next 10 years. Of course, this change does not completely eliminate the desktop software, and the existing browser does not have a desktop program like Photoshop to deal with complex images. But we cannot ignore the impact of it.

3, about the name of Ajax

The full name of Ajax is asynchronous JavaScript and XML, where asynchronous is asynchronous and differs from the way in which traditional web development uses synchronization.

4. About synchronous and asynchronous

Asynchronous transmission is a character-oriented transmission, its unit is a character, and synchronous transmission is a bit-oriented transmission, its unit is frame, it is transmitted when the receiver and the sender's clock is consistent.

Specifically, asynchronous transmission is the transfer of bits into groups. Typically each group is a 8-bit character, in the head and tail of each group has a start bit and a stop bit, it in the transmission process the receiver and the sender's clock does not require the same, that is, the sender can send these groups at any time, and the receiver does not know when it arrives. One of the most obvious examples is the computer keyboard and host communication, press a key while sending a 8-bit ASCII code to the host, the keyboard can send code at any time, depending on the user's input speed, the internal hardware must be able to receive a typed character at any moment. This is a typical asynchronous transfer process. There is a potential problem with asynchronous transmissions, where the receiver does not know when the data will arrive. The first bit has passed before it detects and responds to the data. It's like someone coming up from behind unexpectedly and talking to you, and you missed out on the first few words before you could react. Therefore, each asynchronous transfer of information begins with a starting bit, which notifies the receiver that the data has arrived, giving the receiver the time to respond, receive, and cache the data bits, and at the end of the transfer, a stop bit indicates the termination of the transmission information. By convention, a line that is idle (without transmitting data) actually carries a signal that represents a binary 1. The start bit of the step transfer makes the signal 0, and the other bits make the signal vary with the data being transmitted. Finally, the stop bit causes the signal to change back to 1, and the signal remains at the next start bit. For example, on the keyboard the number "1", according to the 8 bit of extended ASCII encoding, will be sent "00110001", at the same time need to precede the 8 bit with a starting bit, the back of a stop bit.

The bit groupings for synchronous transmissions are much larger. Instead of sending each character independently, each character has its own start and stop bits, but it combines them together to send. We call these combinations a data frame, or simply a frame.

The first part of the data frame contains a set of synchronized characters, which is a unique bit combination, similar to the starting bit mentioned earlier, to inform the receiver that a frame has arrived, but it also ensures that the receiver's sampling speed and the speed of the bit are consistent, so that the sending and receiving parties enter the synchronization.

The last part of the frame is a frame end tag. Like a synchronous character, it is also a unique bit string, similar to the stop bit mentioned earlier, to indicate that there is no other data to arrive at the beginning of the next frame.

Synchronous transmissions are often much faster than asynchronous transmissions. The receiver does not have to start and stop the operation for each character. Once a frame synchronization character is detected, it receives them when the next data arrives. In addition, the overhead of synchronous transmission is relatively low. For example, a typical frame might have 500 bytes (that is, 4000 bits) of data, which might contain only 100 bits of overhead. At this point, the increased bit bit increases the total number of bits transmitted by 2.5%, which is much smaller than the 25 increment in asynchronous transmissions. As the actual bit of data in the data frame increases, the percentage of overhead bits will be reduced accordingly. However, the longer the data bit, the greater the buffer required to cache the data, which limits the size of one frame. In addition, the larger the frame, the longer it occupies the continuous time of the transmission media. In extreme cases, this will cause other users to wait too long.

Once you understand the concepts of synchronization and asynchrony, you should be clear about why Ajax can improve the user experience, which takes the form of asynchronous requests. For example, if your home is now in the community because of some situation and water, now the relevant departments announced two programs, one is completely water off 8 hours, in this 8 hours completely water, 8 hours after the return to normal. Two is not completely water off 10 hours, in this 10 hours of water is not completely broken, but the flow is much smaller than the original, after 10 hours to return to normal flow, then, if it is you you will choose which way? Obviously the latter.

5. The technology that Ajax contains

We all know that Ajax is not a new technology, but a combination of several original technologies. It is a combination of the following technologies.

1. Use CSS and XHTML to represent.

2. Use the DOM model for interactive and dynamic display.

3. Use XMLHttpRequest to communicate with the server asynchronously.

4. Use JavaScript to bind and invoke.

In the above technology, in addition to the XMLHttpRequest object, all other technologies are based on web standards and has been widely used, xmlhttprequest although not yet accepted by the website, but it is a fact of the standard, Because it is currently supported by almost all major browsers.

6. Ajax Principles and XMLHttpRequest objects

The principle of Ajax is simply to send an asynchronous request to the server via the XMLHttpRequest object, get the data from the server, and then use JavaScript to manipulate the DOM and update the page. One of the most critical steps is getting the request data from the server. To understand this process and principle, we must have some knowledge of xmlhttprequest.

XMLHttpRequest is the core mechanism of Ajax, which was first introduced in IE5 and is a technique that supports asynchronous requests. Simply put, JavaScript can request and process responses to the server in a timely manner without blocking the user. Achieve a 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 event handlers for events that are triggered by each state change.

ResponseText the string form of the data returned from the server process.

Responsexml a DOM-compatible document data object that is returned from the server process.

Status number codes returned from the server, such as common 404 (not Found) and 200 (ready)

Status Text string information accompanying the state code

ReadyState Object State Value

0 (uninitialized) object has been established but not initialized (the open method has not been called)

1 (Initialize) object has been established, the Send method has not been called

2 (send data) The Send method has been called, but the current state and HTTP headers are unknown

3 (data transfer) has received some of the data, because the response and HTTP header is not complete, then through Responsebody and ResponseText to obtain some of the data will be error,

4 (complete) The data is received, at which time the complete response data can be obtained by Responsexml and ResponseText

However, because there are differences between browsers, creating a XMLHttpRequest object may require different methods. This difference is mainly between IE and other browsers. The following is a more standard way to create a XMLHttpRequest object.

function createxmlhttp () {//non IE browser creates XMLHttpRequest object if (window.    XMLHttpRequest) {xmlhttp = new XMLHttpRequest (); The//ie browser creates the XMLHttpRequest object 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 ("Create XMLHTTP Object Exception!        ");    return false;    } ("POST", url, false); Xmlhttp.onreadystatechange = function () {if (xmlhttp.readystate = = 4) {document.getElementById ("User1            "). InnerHTML =" Data is loading ... ";            if (Xmlhttp.status = =) {document.write (xmlhttp.responsetext); }}} xmlhttp.send ();} 

As shown above, the function first checks the overall state of the XMLHttpRequest and ensures that it has been completed (readystatus=4), that is, the data has been sent. The request status is then queried based on the server's settings, and if everything is ready (status=200), perform the actions required below.

For XMLHttpRequest two methods, open and send, where the Open method specifies:

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

b, the requested URL address and the passed parameters.

C, transmission mode, false is synchronous, true is asynchronous. The default is true. In the case of asynchronous communication (true), the client does not wait for the server to respond, and if it is synchronous (false), the client waits until the server returns the message before performing other operations. We need to specify the synchronization according to the actual needs, in some pages, may make multiple requests, even the organization has a plan to form a large-scale high-intensity request, the next one will overwrite the previous one, this time of course to specify the synchronization mode.

The Send method is used to send the request.

Knowing the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server, 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, Make requests and respond to requests. And it's completely a client-side technology. And XMLHttpRequest is dealing with the server side and client communication problems, so it is so important.

Now, we probably have an understanding of the principles of Ajax. We can think of the server as a data interface, which returns a plain text stream, of course, the text stream can be in XML format, can be HTML, can be JavaScript code, can be just a string. At this time, XMLHttpRequest to the server side to request this page, the server side writes the results of the text to the page, which is the same as the normal web development process, the difference is that the client asynchronously obtains this result, is not directly displayed on the page, but first by the JavaScript processing, Then the page appears again. As for many of the Ajax controls that are now popular, such as Magicajax, you can return other data types such as datasets, but only encapsulate the results of this process, and they are not much different in nature.

7, the advantages of Ajax

Ajax to bring us the benefits of all of you are basically deep experience, here I only briefly say a few points:

1, the biggest point is that the page does not refresh, in the page and the server to communicate with the user experience is very good.

2, using the asynchronous way to communicate with the server, do not need to interrupt the user's operation, with more rapid response.

3, can transfer the work of some previous server to the client, take advantage of the client idle ability to handle, reduce the burden of server and bandwidth, save space and broadband rental cost. and reduce the burden on the server, the principle of Ajax is "on-demand data", can minimize redundancy requests, and response to the burden on the server.

4, based on standardized and widely supported technology, do not need to download plug-ins or small programs.

8, the shortcomings of Ajax

Let me focus on the drawbacks of Ajax, because most of the things we pay attention to are the benefits of Ajax, such as the improvement of the user experience. And the shortcomings of Ajax have been neglected.

The drawbacks of Ajax described below are inherently generated.

1, Ajax killed the back button, that is, the browser fallback mechanism of destruction. The Back button is an important feature of a standard web site, but it does not work well with JS. This is a serious problem with Ajax, because users often want to be able to undo the previous operation by going backwards. So is there any way to do this question? The answer is yes, using Gmail know, Gmail under the Ajax technology to solve the problem, in Gmail can be back, but it does not change the mechanism of Ajax, it is only a relatively stupid but effective way, that is, the user click the Back button to access the history To reproduce the changes on the page by creating or using a hidden iframe. (for example, when a user clicks back in Google Maps, it searches in a hidden iframe and then reflects the search results on an AJAX element to restore the application state to its current state.) )

However, although this problem can be solved, but the development cost of it is very high, and the AJAX framework required by the rapid development is a divergence. This is a very serious problem caused by Ajax. (Want to see more on the Topic.alibabacloud.comAJAX Development Manual section of the study)

2, security issues

Technology also poses new security threats to IT companies, and Ajax technology is just like building a direct channel to enterprise data. This allows developers to inadvertently expose more data and server logic than ever before. The logic of Ajax can be hidden from the client's security scanning technology, allowing hackers to create new attacks from remote servers. And Ajax also makes it difficult to avoid some known security weaknesses, such as cross-site footstep attacks, SQL injection attacks, and credentials-based security vulnerabilities.

3, the support of the search engine is weaker.

4. The abnormal mechanism of the program is destroyed. At least for now, these Ajax frameworks, like Ajax.dll,ajaxpro.dll, can disrupt the program's exception mechanism. On this issue, I have encountered in the development process, but looked at the Internet almost no relevant introduction. Then I did a test by myself, using Ajax and the traditional form submission mode to delete a piece of data ... It has brought us a lot of difficulties in debugging.

5, in addition, like some other aspects of the problem, such as violating the URL and resource positioning of the original intention. For example, I give you a URL address, if you use Ajax technology, perhaps you see below the URL address and what I see under this URL is different. This is contrary to the original intention of resource positioning.

6, some handheld devices (such as mobile phones, PDAs, etc.) are not very good to support Ajax, for example, we open the browser on the mobile phone using AJAX technology site, it is currently not supported, of course, this problem and we do not have much to do with.

9. Several frameworks of Ajax

The more Ajax frameworks we use today are mainly Ajax.dll,ajaxpro.dll,magicajax.dll and Microsoft's Atlas framework. Ajax.dll and Ajaxpro.dll These two frameworks are not very different, and Magicajax.dll just package more, for example, it can directly return the dataset dataset, as we have said before, Ajax is returning a string, Magicajax just encapsulated it. But this feature can bring us a lot of convenience, for example, our page has a list, and the list of data is constantly changing, then we can use Magicajax to deal with, the operation is very simple, after adding Magicajax, The list control to be updated is placed within the Magicajax control, and the time to define the update interval within the pageload is OK, and the principle of Atlas is similar to Magicajax. However, one of the problems to be aware of is that these frameworks only support IE, do not do browser-compatible aspects of the processing, with the anti-compilation tools to see their code can be known.

In addition to these frameworks, the more common way we use them is to create XMLHttpRequest objects ourselves, which is more flexible than the previous frameworks. In addition, here also mention the aspnet2.0 of the asynchronous callback interface, it can also be implemented as Ajax partial non-flush, but its implementation is actually based on the XMLHttpRequest object, but also only support IE, of course, this is Microsoft's competitive strategy.

10. Ajax Example

Verify that the user name is registered.

There are two ways of using

1 Ajax.dll

2 Write XMLHttpRequest Object yourself

Some of the errors that are common in 10.ajax

1 Problems with configuration

When configuring this page in Pageload

Call the foreground part in the method called in the background ...

This is the end of this article (want to see more on the Topic.alibabacloud.comAJAX User manual section of the study), there are questions can be in the message below the question.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.