function Myajax (options) {
Create a new local object to hold various parameters for user input
var opt={
type:options.type| | " Get ",//Get user input transfer method, optional, not write as Get
data:options.data| | "",//Get the data entered by the user
datatype:options.datatype| | "",//Get user input data type such as JSON or XML
url:options.url| | "",//URL entered by user
success:options.success| | null//the success function.
}
if (opt.url== "") {//If the user does not enter a URL, this is not allowed. Return directly, do not perform future operations
alert ("URL cannot be empty");
return;
}
if (options.type) {
opt.type=options.type.tolowercase ()//Convert user-entered post and other methods into lowercase
}
//Create a new Connection object. The XMLHttpRequest object is created in the standard browser. New ActiveXObject in non-standard browsers
var xhr=null;
try{
xhr=new XMLHttpRequest;
}catch (e) {
xhr=new ActiveXObject ("micsoft.xmlhttp");
}
//If the user uses the Get method, it is necessary to splice the URL, put the user's data into the URL to the background
if (opt.type== "get" &&opt.data) {
opt.url+= "?" +opt.data;
}
Xhr.open (opt.type,opt.url,true);//Call the Xhr.open method to connect the background excuse
//If it is a GET method, the Send function does not pass a value,
if (opt.type= "get") {
xhr.send (null);
}else{
//If the Post method requires a connection header. And the incoming user's data in the Send function
xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
xhr.send (opt.data);
}
//connection completed, and other background return results and data
xhr.onreadystatechange=function () {
if (xhr.readystate==4) {//readystate has 5 status codes. 0,1,2,3,4
if (xhr.status==200) {//http Status code = 200 means success
var data=xhr.responsetext;//create a new variable save the data returned in the background
if (opt.dataType.toLowerCase () = = "xml") {
data=xhr.responsexml;//If the background returns the data in XML format. Use Responsexml to get
}
if (opt.dataType.toLowerCase () = = "json") {
data=json.parse (data);//If it is JSON, use parse to convert the string to an object
}
if (typeof opt.success=== ' function ') {
opt.success (data);//If a successful callback function returns the background data to the past as a parameter of the callback function
}
}else{
alert ("Error" +xhr.status)//If the status code is not 200, the connection fails, and the HTTP status code is returned
}
}
}
}
Add:
Status code meaning of readystate
0: Request not initialized
1: Server Connection established
2: Request Accepted
3: In Request processing
4: The request is complete and the response is ready.
Native JavaScript encapsulates Ajax