Ajax timeout Verification, the 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; To store an instance of a XMLHttpRequest object with a property
}
Ajax.prototype.send=function (url,options) {
if (!this. XHR) return;
var xhr=this. XHR;
var Aborted=false;
var _options={//provide 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 transmission
}
}
Check the value of the ReadyState property within the specified time
SetTimeout (checkfortimeout,_options.timeout);
function Onreadystatecallback () {
if (xhr.readystate==4) {
/*
* Note: status code in 200 for success, 300 for redirection, 400 is a client error, 500 is a server-side error
*/
if (!aborted && xhr.status>=200 && xhr.status<300) {//Check aborted property timeout
_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>