用户登录
用户注册

分享至

Ajax 超时检查脚本

  • 作者: 在下灬醉墨
  • 来源: 51数据库
  • 2021-09-02
复制代码 代码如下:

<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(){},
onsuccess: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.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>
软件
前端设计
程序设计
Java相关