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(){},
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>