Copy codeThe Code is as follows :/**
* @ Author Supersha
* @ QQ: 770104121.
*/
<! Doctype html public "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Ajax Document </title>
<Script type = "text/javascript">
// Note: the encoding must be UTF-8 in order to avoid Chinese parameter and Chinese garbled characters returned.
Function Ajax (prop ){
This. action (prop); // call the action method during instantiation
}
Ajax. prototype = {
CreateXHR: function () {// create an XMLHttpRequest object
Var xhr = false;
If (window. XMLHttpRequest ){
Xhr = new XMLHttpRequest ();
}
Else
If (window. ActiveXObject ){
Try {
Xhr = new ActiveXObject ("Msxml2.XMLHTTP ");
}
Catch (e ){
Xhr = new ActiveXObject ("Microsoft. XMLHTTP ");
}
}
Return xhr;
},
Action: function (prop ){
Var xhr = this. createXHR ();
If (xhr ){
Var url = encodeURI (prop ["url"]); // encode the URL
If (prop ["method"] = "GET" & url & prop ["success"]) {// GET method
Xhr. onreadystatechange = function (){
(Function () {// The self-executed function is used to check the return status of the server and execute the callback function.
If (xhr. readyState = 4 & xhr. status = 200 ){
Prop ["success"] (xhr); // executes the callback function
}
})();
};
// Alert (prop ["hander"] instanceof Function );
Xhr. open ("GET", url, true );
Xhr. send (null );
}
Else
If (prop ["method"] = "POST" & url & prop ["success"]) {// POST method
Xhr. onreadystatechange = function (){
(Function (){
If (xhr. readyState = 4 & xhr. status = 200 ){
Prop ["success"] (xhr); // executes the callback function
}
})();
};
If (prop ["params"]) {
Url = url. indexOf ("? ")>-1? Url + "&" + prop ["params"]: url + "? "+ Prop [" params "];
}
Xhr. open ("POST", url, true );
Xhr. setRequestHeader ("Content-type", "application/x-www-form-urlencoded ");
Xhr. send (null );
}
}
Else
If (! Xhr & prop ["fail"]) {
Prop ["fail"] ();
}
}
}
Function getData (){
Var ajax = new Ajax ({
Url: "test. php ",
Method: "POST ",
Success: onComplete,
Params: "name =" + escape ("Shaofeng") // encode
});
}
Function onComplete (obj ){
Alert (unescape (obj. responseText); // transcode
}
</Script>
</Head>
<Body>
<Input type = "button" value = "Get Data" onclick = "getData ()"/>
</Body>
</Html>
Note:
The Ajax object accepts an object literal as a parameter, which contains the method, url, success, params, and fail parameters.
Method: "GET" or "POST"
Url: Server File Path
Success: the callback function called when the request is correct. The callback function includes a parameter of the XMLHttpRequest object.
Fail: called when a request is incorrect
Params: when a request is sent using the POST method, params is the parameter string.