Ajax 逾時檢查指令碼_AJAX相關

來源:互聯網
上載者:User
複製代碼 代碼如下:

<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>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.