For xhr objects, we mainly access the server asynchronously and process the server response content in the onreadystatechange event. The simple xhr usage is as follows.
The Code is as follows:
// Create an XHR object
Var xhr;
If (window. XMLHttpRequest ){
Xhr = new XMLHttpRequest ();
}
Else if (window. ActiveXObject ){
Xhr = new ActiveXObject ("Msxml2.XMLHTTP ");
}
Else {
Throw new Error ("Ajax is not supported by this browser ");
}
Function ready ()
{
Alert ("Start ......");
// Process asynchronous requests through events
Xhr. onreadystatechange = function ()
{
If (xhr. readyState = 4)
{
Alert ("Ready .");
If (xhr. status = 200)
{
Alert ("the result returned by the server is successfully obtained .");
// After the request ends, you can obtain the content returned by the server.
Alert (xhr. responseText );
// Obtain the json object returned by the server
Var alice = eval ("(" + xhr. responseText + ")");
Alert (alice. name );
}
}
};
// Set Request Parameters
Xhr. open ("get", "data. json ");
Xhr. send (null );
}
JQuery simply encapsulates the use of xhr objects. By adding common access methods to jQuery objects, jQuery objects are provided for use.
The Code is as follows:
// The main extension is in jQuery. ajax.
JQuery. extend ({/// #6299
// Default Request Parameters
AjaxSettings :{
Url: location. href,
Type: "GET ",
ContentType: "application/x-www-form-urlencoded ",
Data: null,
Xhr: window. XMLHttpRequest & (window. location. protocol! = "File:" |! Window. ActiveXObject )?
Function (){
Return new window. XMLHttpRequest ();
}:
Function (){
Try {
Return new window. ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){}
}
},
// Set jQuery. ajaxSettings and Request Parameters
AjaxSetup: function (settings ){
JQuery. extend (jQuery. ajaxSettings, settings );
},
Ajax: function (origSettings) {// actual ajax function
Var s = jQuery. extend (true, {}, jQuery. ajaxSettings, origSettings );
// Create an xhr object
Xhr = s. xhr ();
// Callback function
Var onreadystatechange = xhr. onreadystatechange = function (isTimeout ){
If (xhr. readyState === 4 ){
If (xhr. status = 200 ){
S. success. call (origSettings, xhr. responseText );
}
}
};
// Set Request Parameters
Xhr. open (s. type, s. url );
// Send the data to Send the request
Xhr. send (s. data );
// Return XMLHttpRequest to allow aborting the request etc.
Return xhr;
},
// Method for sending ajax requests using get
Get: function (url, data, callback, type ){
// Shift arguments if data argument was omited
If (jQuery. isFunction (data )){
Type = type | callback;
Callback = data;
Data = null;
}
Return jQuery. ajax ({
Type: "GET ",
Url: url,
Data: data,
Success: callback,
DataType: type
});
}
}); // #6922
// Expand the jQuery object and add the load Method
JQuery. fn. extend (
{
Load: function (url ){
Var self = this;
JQuery. get (url, function (data ){
Self. each (function (){
This. innerHTML = data;
}
)
}
)
}
}
)
On the page, you can use the following.
The Code is as follows: