Ajax 超时检查脚本

网络编程 2021-07-05 10:37www.168986.cn编程入门
检查Ajax 是否超时的脚本代码
代码如下:

<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; //用属性存储XMLHttpRequest对象的实例
}
Ajax.prototype.send=function(url,options){
if(!this.Xhr) return;
var xhr=this.Xhr;
var aborted=false;
var _options={ //提供默认值
method:"GET",
timeout:5000,
onerror:function(){},
onsuess:function(){}
};
for(var o in options){ //覆盖掉原来的默认值
_options[o]=options[o];
}
function checkForTimeout(){ //检查是否超时的情况
if(xhr.readyState!=4){
aborted=true;
xhr.abort(); //取消本次传输
}
}
//在规定的时间内检查readyState属性的值
setTimeout(checkForTimeout,_options.timeout);
function onreadystateCallback(){
if(xhr.readyState==4){
/
注释状态码在200内表示成功,300内表示重定向,400内是客户端错误,500是服务器端错误
/
if(!aborted && xhr.status>=200 && xhr.status<300){ //检查aborted属性是否超时
_options.onsuess(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,onsuess:onsuess});
function onerror(xhr){
alert("Timeout");
}
function onsuess(xhr){
alert(xhr.responseText);
}
</script>

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by