Ajax method: Load remote data through HTTP requests
Get method: load information through a remote http get request
POST method: load information through a remote http post request
1. Create an XMLHTTPRequest object
Function createxhr (){
Return window. XMLHttpRequest? New XMLHttpRequest (): New activexobject ("Microsoft. XMLHTTP ");
}
2. convert a key-value pair to a concatenation string
Function Params (data ){
VaR A = [];
For (var I in data ){
A. Push (encodeuricomponent (I) + "=" + encodeuricomponent (data [I]);
}
Return A. Join ("&");
}
3. encapsulate Ajax Methods
Parameters
Method Request methods get and post default get
Data key-Value Pair {key: Value}
URL
Cache true and false default true with Cache
Success success error exception
Function Ajax (ARGs ){
VaR xhr = createxhr ();
VaR DATA = Params (ARGs. data );
If (/get/I. Test (ARGs. Method) {// when the get method is used, the data is directly spliced to the URL.
Args. url + = "? "+ Data;
}
If (! Args. cache) {// No Cache
If (ARGs. url. indexof ("? ") <0) {// when no data parameter exists
Args. url + = "? ";
}
Args. url + = "&" + (new date (); // math. Random ();
}
Xhr. Open (ARGs. method, argS. url, true );
Xhr. onreadystatechange = function (){
If (4 = xhr. readystate & 200 = xhr. Status ){
Args. Success (xhr. responsetext, xhr. responsexml );
}
Else {
Args. Error ();
}
}
If (/post/I. Test (ARGs. Method )){
Xhr. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
Xhr. Send (data );
}
Else {
Xhr. Send ();
}
}
4. This is a simple get Method Request function to replace complex Ajax methods. You can call the callback function when the request is successful. To execute a function when an error occurs, use the Ajax method.
Function get (URL, Data, FN ){
Ajax ({"method": "Get", "url": URL, "data": data, "success": fn });
}
5. This is a simple post Method Request function to replace the complex Ajax method. You can call the callback function when the request is successful. To execute a function when an error occurs, use the Ajax method.
Function post (URL, Data, FN ){
Ajax ({"method": "Post", "url": URL, "data": data, "success": fn });
}