jquery getJSON 中對超時Timeout的處理


調用 jquery1.4 的getJSON()方法時,如下代碼就能處理當URL為非法URL,或者URL繁忙而不能返回響應、超時等狀況。代碼源自 http://stackoverflow.com/questions/4138470/jquery-getjson-with-timeout

function
testAjax(){
       
varparams="test=123";
       
var isneedtoKillAjax =true;// set this true

       
// Fire the checkajaxkill method after 10 seonds
        setTimeout
(function(){
            checkajaxkill
();
       
},10000);// 10 seconds                

       
// For testing purpose set the sleep for 12 seconds in php page

$.getJSON('index2.php',params,function(data, textStatus){              
            isneedtoKillAjax
=false;// set to false
           
// Do your actions based on result (data OR textStatus)
       
});

       
function checkajaxkill(){

           
// Check isneedtoKillAjax is true or false,
           
// if true abort the getJsonRequest

           
if(isneedtoKillAjax){
                //myAjaxCall
.abort();
                alert
('killing the ajax call');                
           
}else{
                alert
('no need to kill ajax');
           
}
       
}
   
}

以上寫法應該成為調用getJSON的時候標准模式,即對timeout這種例外的一種必須的處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM