Copy Code code as follows:
/**
* @author Supersha
* @QQ: 770104121
*/
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>ajax document</title>
<script type= "Text/javascript" >
Note that the encoding should be agreed to utf-8 to avoid Chinese parameters and the garbled problem of returning Chinese
function Ajax (prop) {
This.action (prop); Call the action method when instantiated
}
Ajax.prototype = {
Createxhr:function () {///Create 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"]); To encode a URL
if (prop["method"] = = "get" && URL && prop["success"]) {//get methods
Xhr.onreadystatechange = function () {
(function () {//The self-execution function checks the return state of the server and executes the callback function
if (xhr.readystate = = 4 && xhr.status = 200) {
prop["Success"] (XHR); Executing a callback function
}
})();
};
Alert (prop["hander"] instanceof Function);
Xhr.open ("Get", url, True);
Xhr.send (NULL);
}
Else
if (prop["methods"] = = "POST" && URL && prop["success"]) {//post method
Xhr.onreadystatechange = function () {
(function () {
if (xhr.readystate = = 4 && xhr.status = 200) {
prop["Success"] (XHR); Executing a 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 ("Sha Feng")//coding
});
}
function OnComplete (obj) {
Alert (unescape (Obj.responsetext)); Make a transfer code
}
</script>
<body>
<input type= "button" value= "Get Data" onclick= "GetData ()"/>
</body>
Comments:
An Ajax object accepts an object literal as a parameter that contains the Method,url,success,params,fail parameter
Method: ' Get ' or ' POST '
URL: server-side file path
Success: The callback function that is invoked when the request has no errors, with a XMLHttpRequest object parameter
Fail: Call when the request is wrong
Params: When sending a request using the Post method, params is a parameter string