// Configure //--------------------------------------------------------------------------------------
// Code that encapsulates the Request class of XMLHTTP
Var $ ajax = new Object ();
Function getAjax (){
Var ajax = false;
Try {
Ajax = new ActiveXObject ("Msxml2.XMLHTTP ");
}
Catch (e ){
Try {
Ajax = new ActiveXObject ("Microsoft. XMLHTTP ");
}
Catch (E ){
Ajax = false;
}
}
If (! Ajax & typeof XMLHttpRequest! = 'Undefined '){
Ajax = new XMLHttpRequest ();
}
Return ajax;
}
// Encapsulate the requests sent from XMLHTTP to the server
$ Ajax. send = function (url, method, callback, data ){
Var req = getAjax (); // get an XMLHTTP instance
// Called when the Request status of XMLHTTP changes
Req. onreadystatechange = function (){
// When the request has been loaded
If (req. readyState = 4 ){
// When the request is returned successfully
If (req. status = 200 ){
// When a successful callback function is defined, the callback function is successfully executed.
If (callback)
Callback (req, data );
}
// When the request returns an error
Else {
Alert ("error occurred when loading data: \ n" + req. status + "/" + req. statusText );
}
Try {
Delete req;
Req = null;
} Catch (e ){}
}
}
// If the POST request is sent back to the sending server
If (method = "POST "){
Req. open ("POST", url, true );
Req. setRequestHeader ('content-type', 'application/x-www-form-urlencoded ');
Req. send (data );
}
// GET request
Else {
Req. open ("GET", url, true );
Req. send (null );
}
}
// Further encapsulate the code when XMLHTTP sends a request in POST Mode
$ Ajax. sendPOST = function (url, data, callback ){
$ Ajax. send (url, "POST", callback, data );
}
// Further encapsulate the code when XMLHTTP sends a request in GET Mode
$ Ajax. sendGET = function (url, callback, args ){
Return $ ajax. send (url, "GET", callback, args );
}
// Configure //--------------------------------------------------------------------------------------
The above code is easy, but the basic ajax requirements are also easy to use:
$ Ajax. sendPOST ("Handler. ashx", "action = reply &" + parameter,
Function (req, data ){
Var rel = req. responseText;
}
);