2012-09-13 51 views
1

我有一個Ajax調用一組網址來獲取html內容。但是,有些網址需要很長時間才能獲得內容,我可以跳過那些需要超過1秒的內容。Jquery ajax調用超時。

for (url in list) { 
    $.ajax({ 
     'url': url, 
     type: 'get', 
     timeout: 1000, 
     success: function() { 
      //doSomething 
     }, 
     complete: function() { 
      //what to write? 
     } 
    }); 

} 

你能幫助我在如何,如果超時終止Ajax調用和執行完整的功能。

讓我知道我不清楚。 謝謝

回答

2

首先,將$.ajax(function() {更改爲$.ajax({,因爲您試圖使用的參數是一個對象,而不是函數。

由於您在選項對象中指定了超時,如果頁面沒有及時響應,只要您指定一個,ajax方法就會告訴您的error函數。

$.ajax({ 
    'url': yourUrlHere, 
    success: function(){ /*do stuff*/ }, 
    timeout: 1000, 
    error: function(xhr, status, err){ 
    //status === 'timeout' if it took too long. 
    //handle that however you want. 
    console.log(status,err); 
    } 
}); 

請參閱the documentation for $.ajax here,因爲它對函數有很好的解釋。

+0

我越來越在狀態「錯誤」而不是「超時」。 – UmaShankar

0

可以中止請求,如果出現這種情況,並繼續到下一個..

var ajaxRequests = null; 
for(url in list){ 
    var newRequest = $.ajax({ 
    type: 'GET', 
    url: url, 
    data: '{}', 
    dataType: 'json', 
    beforeSend: function() { 
     var r = ajaxRequest; 
     if (r != null && r != undefined) { 
      r.abort(); 
     } 
    }, 
    success: function(result) { 
     // what has to be done if the ajax request comes through 
    }, 
    complete: function() { 
     ajaxRequests = null; 
    } 
    ajaxReqs = newRequest; 
}