Ajax 超時檢查腳本
來源:懂視網
責編:小采
時間:2020-11-27 22:52:35
Ajax 超時檢查腳本
Ajax 超時檢查腳本: 代碼如下:<script type=text/javascript> function Ajax(){ var xhr; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else{ try{xhr=new ActiveXObject(MSXML2.XMLHTTP.6.0);
導讀Ajax 超時檢查腳本: 代碼如下:<script type=text/javascript> function Ajax(){ var xhr; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else{ try{xhr=new ActiveXObject(MSXML2.XMLHTTP.6.0);

代碼如下:
<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>
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
Ajax 超時檢查腳本
Ajax 超時檢查腳本: 代碼如下:<script type=text/javascript> function Ajax(){ var xhr; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else{ try{xhr=new ActiveXObject(MSXML2.XMLHTTP.6.0);