Principles and operating mechanisms of AJAX

Source: Internet
Author: User
Ajax is a very popular technology recently. It is also very popular nowadays. Of course, it is not a new technology, but a unity under various existing technologies and support mechanisms. In my projects, Ajax is occasionally used to give users a fresh experience. After using it several times, I personally decided to summarize its principles and operating mechanisms.
The Ajax name is said to be short for Asynchronous JavaScript + XML. In fact, it is composed of the following technologies.

1. CSS and XHTML are used for representation.
2. Use the DOM model for interaction and dynamic display.
3. Use XMLHttpRequest to communicate with the server asynchronously.
4. Use JavaScript for binding and calling.

Principles of AJAX
XMLHttpRequest is the core mechanism of Ajax. It is first introduced in ie5. it is a technology that supports asynchronous requests. Simply put, JavaScript can promptly request and process responses to the server without blocking users. Achieve the effect of refreshing.
So let's start with XMLHttpRequest to see how it works.
First, let's take a look at the attributes of the XMLHTTPRequest object.
Its attributes include:
Onreadystatechange event processing triggered by each state changeProgram.
The string format of responsetext returned data from the server process.
Responsexml is a dom-compatible document data object returned by the server process.
Number returned by the server for statusCode, Such as common 404 (not found) and 200 (ready)
String information of the Status text accompanied by the status code
Readystate object status value, 0-not initialized 1-loading 2-Loading completed 3-interaction 4-finished.

However, because of the differences between browsers, creating an XMLHTTPRequest object may require different methods. This difference is mainly reflected in IE and other browsers.
The following lists the XMLHttpRequest objects created in different browsers.

<Script Language="Javascript"Type="Text/JavaScript">
VaRXMLHTTP= False ;
//Create an XMLHTTPRequest object for IE
Try  {< br> /// use a version of MSXML to create
XMLHTTP = New activexobject ( " msxml2.xmlhttp " );
}  Catch(E) {
Try  {< br> /// use another object to create
XMLHTTP = New activexobject ( " Microsoft. XMLHTTP " );
}  Catch(E2) {
XMLHTTP= False;
}
}

If ( ! XMLHTTP & typeof XMLHttpRequest ! = 'undefined') {
//Create an XMLHTTPRequest object for other non-Microsoft browsers
XMLHTTP= NewXMLHttpRequest ();
}
</Script>

This process is divided into three steps. First, we define an XMLHTTP to reference the created XMLHttpRequest. Then, we try to create this object in Microsoft's browser, first use MSXML. create an XMLHTTP object. If it fails, try macrosoft again. XMLHTTP to create it. finally, we create this object for a non-micro-soft browser.
In this way, we have created an XMLHTTPRequest object. Let's see how to send an XMLHttpRequest request.

Function Executexmlhttprequest (callback, URL)
{
//Handling non-Microsoft browsers
 If (Window. XMLHttpRequest)
  {< br> xhr = New XMLHttpRequest ();
xhr. onreadystatechange = callback;
xhr. open ( " Get " , URL, true );
xhr. send ( null );
}
//Handling of Web browsers
 Else If (Window. activexobject)
  {
Xhr=NewActivexobject ("Macrosoft. XMLHTTP" );
If (Xhr)
{
Xhr. onreadystatechage=Callback;
Xhr. Open ("Get", URL,True);
Xhr. Send ();
}
}

As shown above, the execution of XMLHttpRequest is actually used to process the differences between browsers. It still needs to be processed differently for different browsers, but it looks very intuitive.
In the above Code, the most important thing is:
Xhr. onreadystatechage = callback it defines the callback function and will be automatically executed once it responds.
Xhr. Open ("" get ", URL, true); true indicates that you want to execute the request asynchronously.

For callback, we have:

FunctionProcessajaxresponse () {
//Status is marked as completed
If(Xhr. readystate= 4) {
//Ready
If (xhr. status = 200 ) {
502 502'Votes '). innerhtml=Xhr. responsetext;
}  Else  {
Alert ("There was a problem retrieving the XML data:
" +
Xhr. statustext );
}
}
}  

That is to say, once the server finishes processing XMLHttpRequest and returns it to the browser, the callback method assigned by xhr. onreadystatechange will be called automatically.

The above is almost the whole workflow of XMLHttpRequest. It first checks the overall status of XMLHttpRequest and ensures that it has been completed (readystatus = 4), and then queries the Request status based on the server settings, if everything is ready (status = 200), perform the following operations.

After learning about the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server. Its role is also limited to this, but its role is the key to the entire Ajax implementation, because Ajax is nothing more than two processes, sending requests and responding to requests. And it is completely a client technology. XMLHttpRequest is so important because it handles the communication between the server and the client.
Now we can have a general understanding of the principles of Ajax. We can regard the server as a data interface, which returns a plain text stream. Of course, this text stream can be in XML format, HTML, or JavaScript code, it can also be a string. At this time, XMLHttpRequest requests this page from the server, and the server writes the text results to the page. This is the same as the normal Web development process, after the client asynchronously obtains this result, it is not directly displayed on the page, but processed by JavaScript first and then displayed on the page. As for many popular Ajax controls such as magicajax, other data types such as dataset can be returned, but the results encapsulated by this process are essentially no big difference.

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: info-contact@alibabacloud.com 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.