Introduction to jQuery asynchronous objects (XMLHttpRequest) and jqueryajax asynchronous
Let's take a look at the asynchronous object 5 callback.
This is a post request,
Copy codeThe Code is as follows:
// 1.00 create an asynchronous object
Var xhr = new XMLHttpRequest ();
// 2.0
Xhr. open ("post", url, params, true );
// 3.0 pass the parameter using the Formdata attribute
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// 4.0 set the callback function
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 & xhr. status = 200 ){
Alert (xhr. responseText );
}
}
// 5.0 PASS Parameters
Xhr. send (params );
Encapsulate an asynchronous object with get requests
In the get request
Xhr. setRequestHeader ("If-Modified-Since", "0"); To clear the cache
And
Copy codeThe Code is as follows:
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
It is for Transmission Mode
In <from method = 'post' type = "">
<From> type can be obtained in three ways, including application/x-www-form-urlencoded.
Copy codeThe Code is as follows:
Var ajaxHelp = {
CreatXHR: function (){
// Create an asynchronous object
Var xhr = new XMLHttpRequest ();
Return xhr;
},
// Ajax get request
AjaxGet: function (url, callBack ){
This. AJaxCommon ("get", url, null, callBack );
},
// Ajax post request
AjaxPost: function (url, params, callBack ){
This. AJaxCommon ("post", url, params, callBack );
},
AJaxCommon: function (method, url, params, callBack ){
// 1.0
Var xhr = this. CreatXHR ();
// 2.0
Xhr. open (method, url, true );
// 3.0
If (method = "get "){
Xhr. setRequestHeader ("If-Modified-Since", "0 ");
} Else {
Xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
}
// 4.0
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 & xhr. status = 200 ){
Var datas = JSON. parse (xhr. responseText );
// Execute the callback function
CallBack (datas );
}
}
// 5.0
Xhr. send (params );
}
};
Ps: In JQuery, there are asynchronous request methods such as $. ajax and $. get/$. Post. The previous package is no longer needed. Amount. Good luck. In fact, the underlying layer is also written like this. JQuery is designed to solve compatibility issues of various browsers.
The above is my understanding of jQuery asynchronous objects (XMLHttpRequest). If you have any omissions, please contact me and add me.