復(fù)制代碼 代碼如下:
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; //用屬性存儲(chǔ)XMLHttpRequest對(duì)象的實(shí)例
}
Ajax.prototype.send=function(url,options){
if(!this.Xhr) return;
var xhr=this.Xhr;
var aborted=false;
var _options={ //提供默認(rèn)值
method:"GET",
timeout:5000,
onerror:function(){},
onsuccess:function(){}
};
for(var o in options){ //覆蓋掉原來的默認(rèn)值
_options[o]=options[o];
}
function checkForTimeout(){ //檢查是否超時(shí)的情況
if(xhr.readyState!=4){
aborted=true;
xhr.abort(); //取消本次傳輸
}
}
//在規(guī)定的時(shí)間內(nèi)檢查readyState屬性的值
setTimeout(checkForTimeout,_options.timeout);
function onreadystateCallback(){
if(xhr.readyState==4){
/*
* 注釋:狀態(tài)碼在200內(nèi)表示成功,300內(nèi)表示重定向,400內(nèi)是客戶端錯(cuò)誤,500是服務(wù)器端錯(cuò)誤
*/
if(!aborted xhr.status>=200 xhr.status300){ //檢查aborted屬性是否超時(shí)
_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>
您可能感興趣的文章:- ajax提交session超時(shí)跳轉(zhuǎn)頁面使用全局的方法來處理
- Ajax請(qǐng)求在數(shù)據(jù)量大的時(shí)候出現(xiàn)超時(shí)的解決方法
- ajax 怎么設(shè)置超時(shí)(一個(gè)action執(zhí)行了2遍)
- 登錄超時(shí)給出提示跳到登錄頁面(ajax、導(dǎo)入、導(dǎo)出)