Basic usage:
Copy codeThe Code is as follows:
Var ajax = new AjaxObj (url );
Ajax. addListener (200, function (r ){
Alert (r );
});
Ajax. send ();
It can also be called consecutively:
Copy codeThe Code is as follows:
Var ajax = new AjaxObj (url). addListener (200, function (r ){
Alert (r );
}). Send ();
You can also customize POST or GET requests and monitor different HTTP status codes. Read the code and try it out :)
Complete code:
Copy codeThe Code is as follows:
AjaxObj = function (url, method, content ){
This. r = null;
This. url = url;
This. method = method;
This. content = content;
This. header = {};
This. header ["Connection"] = "close ";
This. header ["Content-type"] = "application/x-www-form-urlencoded ";
Var self = this;
If (window. XMLHttpRequest ){
This. r = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
Try {
This. r = new ActiveXObject ("Msxml2.XMLHTTP ");
} Catch (e ){
Try {
This. r = new ActiveXObject ("Microsoft. XMLHTTP ");
} Catch (e ){
}
}
}
This. addListener = function (http_status, func ){
If (! This. L)
This. L = [];
This. L [http_status] = func;
Return this;
};
This. setHeader = function (name, value ){
This. header [name] = value;
This. r. setRequestHeader (name, value );
Return this;
};
This. send = function (){
If (this. method! = "Post" & this. method! = "Get ")
This. method = "get ";
This. r. open (this. method, this. url, true );
For (var h in this. header ){
This. r. setRequestHeader (h, this. header [h]);
}
This. r. send (this. content );
};
If (this. r) this. r. onreadystatechange = function (){
If (self. r. readyState = 4 & self. L [self. r. status]! = Null)
Self. L [self. r. status] (self. r. responseText );
};
};