Ajax Understanding and Workflow

Source: Internet
Author: User

First, what is Ajax

Ajax is an asynchronous communication technology. Before the advent of Ajax, the client communicates directly with the server. After introducing Ajax, the client and the server add a third-party--ajax. With Ajax, with a small amount of data exchange in the background and the server, you can achieve a partial refresh without refreshing the entire page. Its principle

Second, XHR object

The core of Ajax technology is the XMLHttpRequest object (abbreviated as XHR). ie7+, FireFox, Opera, Chrome, and Safari all support native XHR objects, and creating XHR objects can be written like this

var New XMLHttpRequest ();

If you want to be compatible with IE6, 7 and how to write

var New ActiveXObject ("Msxml2,xmlhttp");

So the compatibility is as follows

1 if (window. ActiveXObject) {2     varnew ActiveXObject ("Msxml2,xmlhttp"); 3 Else {4     var New XMLHttpRequest (); 5 }

Iii. usage of XHR

After creating the Xhr object, to call the open () method to create a request, the open () method accepts three parameters:

1. Type of request to be sent (e.g. "get", "post", etc.)

2. URL of the request

3. A Boolean value that indicates whether the request is sent asynchronously (by default, true, which means async)

Xhr.open ("Get", "index.php",true);

The post () Request method as in the following code

Xhr.open ("Get", "index.php",true); // The post () method must precede the Send () method with the following code xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded") ;

Note: URLs can also be used with absolute paths relative to the current page of the execution code

After the preparation is done, call the Send () method to send the request,

Xhr.send (null);

The data transferred by the Get method is already placed in the URL, and the parameter can be set to NULL

After the Send () method is called, the request is dispatched to the server, Onreadychange captures the requested status code, and detects

The Onreadychange object has a ReadyState property whose value represents the current active stage with the following values:

0: not initialized. The open () method has not been called

1: Start. The open () method has been called, but the Send () method has not been called

2: Send. The Send () method has been called, but the response has not been received

3: Receive. Part of the response data has been accepted

4: Complete. All response data has been accepted and can be used on the client

We just need to determine if the value of readystate is 4 to know that all the data is ready.

1Xhr.onreadystatechange =function(){2     if(xhr.readystate==4) {3         //determine if the status code is successful4         if(xhr.status>=200&&xhr.status<=207| | xhr.status==304) {5             //Call Ajax's ResponseText property to return data6 alert (xhr.responsetext);7}Else{8 alert (xhr.status);9     }  Ten}

Iv. Summary

The native Ajax request is summarized in six steps

1. Create a Xhr object

2. Call the Open () method to create the request

3. Calling the Send () method sends the request

Status code for 4.onreadychange capture request

5. Determine if the status is successful

6. Call Ajax's ResponseText property to return data

1 //Stitching Path2 functiontourl (URL, data) {3     //Get time stamp4     varTime =NewDate (). GetTime ();5Data.time =Time ;6     vararr = [];7      for(varIinchdata) {8         varstr = i + "=" +Data[i];9         //["User" = ' Lili ', "pass" = "4564522", Time= "145486456"]Ten Arr.push (str); One     } A     varstr = Arr.join ("&");//"user=lili&pass=4564522&time=145486456" -     varPath = URL + "?" +str; -     returnpath; the } - functionFnajax (obj) { -     vardata = obj.data| | {};//Optional, if you do not have data, create a new -     varPath =Tourl (obj.url,data); +     varSendtype = obj.sendtype| | " Get; -     varSUCCFN = obj.succfn| |false; +     varFAILFN = obj.failfn| |false; A     //1. Create a XMLHttpRequest object at     //compatible wording -     if(window. ActiveXObject) { -         varAjax =NewActiveXObject ("Msxml2,xmlhttp");//compatible with IE6, 7 -}Else { -         varAjax =NewXMLHttpRequest ();//Modern Browsers -     } in     //2. Create a request -     varTime =NewDate (). GetTime (); to     //determine the type of transmission +     if(sendtype== "Get") { -Ajax.open ("Get", path); the ajax.send (path); *}Else{ $         varPatharr = Path.split ("?"));Panax NotoginsengAjax.open ("Post", patharr[0]);//patharr[0]? Previous content -         //url = "test.txt?time=12365478" the         //3. Send Request +         //the data transferred by the Get method is already placed in the URL, and the parameter can be set to null AAjax.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); theAjax.send (patharr[1]);//patharr[1]? After the content +     } -     //4, the status of the detection request $Ajax.onreadystatechange =function() { $         //if the preparation state of an Ajax object changes execution events -         //The onreadystatechange event is triggered when the ReadyState property has changed . -         //The value of readystate represents the state of the current request and can be handled differently in the event handler based on that value.  the         //5. Determine the status of the request -         if(Ajax.readystate = = 4) {Wuyi             //6. Judging the request result the             if(Ajax.status >= && ajax.status <= 207 | | ajax.status = 304) { -                 //7, the request successfully received the results of the return Wu                 if(SUCCFN) { - SUCCFN (ajax.responsetext); About                 } $}Else { -                 if(FAILFN) { - FAILFN (ajax.status); -                 }                 A             } +         } the     } -}
View Code

Ajax Understanding and Workflow

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.