Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Ajax (){
Var xhr;
If (window. XMLHttpRequest ){
Xhr = new XMLHttpRequest ();
} Else {
Try {xhr = new ActiveXObject ("MSXML2.XMLHTTP. 6.0");} catch (e ){}
Try {xhr = new ActiveXObject ("MSXML2.XMLHTTP");} catch (e ){}
}
If (! Xhr) return;
This. Xhr = xhr; // use attributes to store the instance of the XMLHttpRequest object
}
Ajax. prototype. send = function (url, options ){
If (! This. Xhr) return;
Var xhr = this. Xhr;
Var aborted = false;
Var _ options = {// provide the default value
Method: "GET ",
Timeout: 5000,
Onerror: function (){},
Onsuccess: function (){}
};
For (var o in options) {// overwrite the original default value
_ Options [o] = options [o];
}
Function checkForTimeout () {// check for timeout
If (xhr. readyState! = 4 ){
Aborted = true;
Xhr. abort (); // cancel this transfer
}
}
// Check the value of the readyState attribute within the specified time
SetTimeout (checkForTimeout, _ options. timeout );
Function onreadystateCallback (){
If (xhr. readyState = 4 ){
/*
* Note: Status Code 200 indicates success, 300 indicates redirection, 400 indicates client errors, and 500 indicates server errors.
*/
If (! Aborted & xhr. status> = 200 & xhr. status <300) {// check whether the aborted attribute times out
_ Options. onsuccess (xhr );
} Else {
_ Options. onerror (xhr );
}
}
}
Xhr. open (_ options. method, url, true );
Xhr. onreadystatechange = onreadystateCallback;
Xhr. send (null );
}
Var ajax = new Ajax ();
Ajax. send ("test. php", {method: GET, timeout: 100, onerror: onerror, onsuccess: onsuccess });
Function onerror (xhr ){
Alert ("Timeout ");
}
Function onsuccess (xhr ){
Alert (xhr. responseText );
}
</Script>