How AJAX works

Source: Internet
Author: User

In the past, I did not focus much on the principle. As long as I could finish the function in the shortest time, maybe it was a matter of time, you can sort out the previous items, haha;

 

The core of Ajax is the JavaScript Object XmlHttpRequest. This object is in Internet Explorer
5 is introduced for the first time. It is a technology that supports asynchronous requests. In short, XmlHttpRequest allows you to use JavaScript to request and process responses to the server without blocking users.

When creating a Web site, executing screen updates on the client gives you great flexibility. The following functions can be completed using Ajax:

Dynamically Update the total number of items in the shopping cart. You do not need to click Update and wait for the server to resend the entire page.


This improves site performance by reducing the amount of data downloaded from the server. For example, on a shopping cart page, when updating the number of items in the basket, the entire page is reloaded, which must download the data of the entire page. If Ajax is used to calculate the new total, the server returns only the new total value, so the required bandwidth is only 1% of the original total.
This eliminates the page refresh for each user input. For example, in Ajax, if you click Next on the page list, the server data will only refresh the list rather than the whole page.

Directly edit table data, rather than requiring users to navigate to a new page to edit data. For Ajax, When you click Edit, You can refresh the static table as an editable table. After you Click Done, you can send an Ajax request to update the server and refresh the table so that it contains static and read-only data.

Everything is possible! Hopefully it will inspire you to start developing your own Ajax-based site. However, before getting started, let's introduce an existing Web site that follows the traditional example of submitting, waiting, and re-displaying. We will also discuss how Ajax improves user experience.

The working principle of Ajax is equivalent to adding an intermediate layer between the user and the server, so that user operations and server responses are asynchronous. In this way, the previous server workload is transferred to the client, which facilitates the idle processing capability of the client to reduce the burden on the server and bandwidth, this saves ISP space and bandwidth rental costs.

We use two examples to verify whether a Pass account exists to describe the actual application of AJAX:

(1) return the server response using a text string to verify the existence of the Netease Pass account;

(2) return a response as an XMLDocument object to verify whether the Kingsoft Pass account exists;

First, we need to use JavaScript to create the XMLHttpRequest class to send an HTTP request to the server, XMLHttpRequest
Class is first introduced by Internet Explorer as an ActiveX object, called XMLHTTP. Later, Mozilla, Netscape, and Safari
The XMLHttpRequest class is also provided in other browsers, but the methods for creating the XMLHttpRequest class are different.

For Internet Explorer, the method for creating XMLHttpRequest is as follows:

Xmlhttp_request = new ActiveXObject ("Msxml2.XMLHTTP. 3.0"); // 3.0 or 4.0, 5.0
Xmlhttp_request = new ActiveXObject ("Msxml2.XMLHTTP"); xmlhttp_request = new
ActiveXObject ("Microsoft. XMLHTTP ");

Because XMLHTTP versions may be inconsistent in different Internet Explorer browsers
Explorer browser, so we need
Create the XMLHttpRequest class in the Explorer browser. The above code is based on different Internet
Explorer to create the XMLHttpRequest class.

For Mozilla, Netscape, Safari, and other browsers, the method for creating XMLHttpRequest is as follows: xmlhttp_request = new
XMLHttpRequest ();

Some Mozilla browsers may not work properly if the server's response does not contain the XML mime-type header.
To solve this problem, if the server response header is not text/xml, you can call other methods to modify the header.

Xmlhttp_request = new XMLHttpRequest ();
Xmlhttp_request.overrideMimeType ('text/xml ');

In practical applications, to be compatible with browsers of different versions, the method for creating the XMLHttpRequest class is generally written as follows:

Try {if (window. ActiveXObject) {for (var I = 5; I --) {try {if (I = 2 ){
Xmlhttp_request = new ActiveXObject ("Microsoft. XMLHTTP");} else {
Xmlhttp_request = new ActiveXObject ("Msxml2.XMLHTTP." + I + ". 0 ");}
Xmlhttp_request.setRequestHeader ("Content-Type", "text/xml ");
Xmlhttp_request.setRequestHeader ("Content-Type", "gb2312"); break;} catch (e ){
Xmlhttp_request = false ;}} else if (window. XMLHttpRequest) {xmlhttp_request
= New XMLHttpRequest (); if (xmlhttp_request.overrideMimeType ){
Xmlhttp_request.overrideMimeType ('text/xml') ;}} catch (e) {xmlhttp_request =
False ;}

After defining how to handle the response, you need to send the request. You can call the open () and send () Methods of the HTTP request class as follows:

Xmlhttp_request.open ('get', URL, true); xmlhttp_request.send (null );

The first parameter of open () is the HTTP Request Method-GET, POST, or the method you want to call supported by any server.
According to HTTP specifications, this parameter must be capitalized; otherwise, Some browsers (such as Firefox) may not be able to process requests.

The second parameter is the URL of the Request page.

The third parameter sets whether the request is in asynchronous mode. If it is TRUE, the JavaScript function will continue to be executed without waiting for the server to respond. This is "A" in "AJAX ".

Create XMLHttpRequest using JavaScript
After the class sends an HTTP request to the server, the next step is to decide what to do when the server receives the response. This tells the HTTP request object which JavaScript function is used to process the response. You can set the onreadystatechange attribute of the object to the name of the JavaScript function to be used, as shown below: xmlhttp_request.onreadystatechange
= FunctionName;

FunctionName is the name of the function created using JavaScript. Do not write it as FunctionName (). Of course, you can also directly create JavaScript code after onreadystatechange, for example, xmlhttp_request.onreadystatechange.
= Function (){

// JavaScript code segment

};

In this function. First, check the Request status. Only when a complete server response has been received can the function process the response. XMLHttpRequest
The readyState attribute is provided to determine the server response.

The value of readyState is as follows:

0 (not initialized)

1 (loading)

2 (loaded)

3 (in interaction)

4 (finished)

So only when readyState = 4, a complete server response has been received can the function process the response. The Code is as follows:

If (http_request.readyState = 4) {// receives the complete Server Response} else {// does not receive the complete Server Response
} When readyState = 4, a complete server response has been received. Then, the function checks the status value of the HTTP server response. For complete status values, see W3C documentation. When the HTTP server response value is 200, the status is normal.

After checking the Request status value and response HTTP status value, you can process the data obtained from the server. There are two ways to obtain the data: (1)
Returns the server response in the form of a text string.

(2) return a response as an XMLDocument object

Example 1: return the server response using a text string to verify the existence of the Netease Pass account

First, log on to the Netease pass registration page and check whether the user name exists. Submit the user name to the checkssn. jsp page for determination. The format is:

Reg.163.com/register/checkssn.jsp? Username = User Name
Based on the method described above, we can use AJAX technology to detect Netease pass usernames:

Step 1: create a web page based on the Xhtml standard and insert the Javascript function in the area as follows:

Function getXMLRequester ()

{Var xmlhttp_request = false; try

{If (window. ActiveXObject)

{For (var I = 5; I --) {try {if (I = 2)

{Xmlhttp_request = new ActiveXObject ("Microsoft. XMLHTTP ");}

Else

{Xmlhttp_request = new ActiveXObject

("Msxml2.XMLHTTP." + I + ". 0 ");

Xmlhttp_request.setRequestHeader

("Content-Type", "text/xml ");
Xmlhttp_request.setRequestHeader ("Content-Type", "gb2312 ");}

Break ;}

Catch (e) {xmlhttp_request = false ;}}}

Else if (window. XMLHttpRequest)

{Xmlhttp_request = new XMLHttpRequest ();

If (xmlhttp_request.overrideMimeType)

{Xmlhttp_request.overrideMimeType ('text/xml ');}}}

Catch (e) {xmlhttp_request = false ;}

Return xmlhttp_request ;}

Function IDRequest (n)

{// Defines the JavaScript function to be executed after receiving the Server Response
Url = n + document. getElementById ('163id'). value;

// Define the URL parameter xmlhttp_request = getXMLRequester ();

// Call the XMLHttpRequest function xmlhttp_request.onreadystatechange = doContents;

// Call the doContents function xmlhttp_request.open ('get', url, true );
Xmlhttp_request.send (null);} function doContents ()

{If (xmlhttp_request.readyState = 4)

{// Receives the complete server response if (xmlhttp_request.status = 200 ){

// HTTP server response value: OK document. getElementById ('message'). innerHTML =
Xmlhttp_request.responseText;

// Write the string returned by the server to the region where the ID is message on the page}

Else {alert (http_request.status );}}}

Create a text box in the region with the id 163id

Create a blank area with id messsge to display the returned string (you can also use the Javascript function to capture some strings for display ):

In this way, a user name detection Page Based on AJAX technology is ready, but this page will return all the strings on the page generated by the server response. Of course, you can also perform some operations on the returned strings, it is easy to apply to different needs.

Example 2: return a response as an XMLDocument object to verify the existence of the Kingsoft Pass account

In the above example, when the server receives the response to the HTTP request, we will call the reponseText attribute of the request object. This attribute contains the content of the response file returned by the server. Now we return a response in the form of an XMLDocument object. At this time, the responseXML attribute is no longer required for the reponseText attribute.

First, log on to the Kingsoft pass registration page and find that the detection method of Kingsoft pass username is:
Pass.kingsoft.com/ksgweb/jsp/login/uid.jsp? Uid = username, and XML data is returned:

IsExistedUid-2

If the result value is-1, it indicates that the user name has been registered. If the result value is-2, it indicates that the user name has not been registered, therefore, you can determine whether the user name is registered by checking the result value.

Modify the code of the previous example:

First find

Document. getElementById ('message'). innerHTML =
Xmlhttp_request.responseText;

Changed:

Var response = xmlhttp_request.responseXML.documentElement;

Var result =
Response. getElementsByTagName ('result') [0]. firstChild. data; // return result node data

If (result =-2 ){

Document. getElementById ('message'). innerHTML =
"Username" + document. getElementById ('163id'). value + "not registered ";}

Else if (result =-1 ){

Document. getElementById ('message'). innerHTML =
"Sorry, username" + document. getElementById ('163id'). value + "registered ";}

The above two examples illustrate the basic AJAX client applications, using Netease And Kingsoft ready-made server-side programs. Of course, to develop programs suitable for your own pages, you also need to write your own server-side programs, this design involves the operation of the program language and database, which is not very difficult for readers who have a certain program base.

More details: http://hi.baidu.com/tang818/blog/item/b201e36e78b214d880cb4a29.html

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.