2013-02-26 58 views
1

我用ajax做了一個GET請求,期望返回一個JSON值。jQuery ajax超時函數?

然而,我的主機安裝了防火牆。它每秒只需要2次請求,否則會阻止連接並顯示錯誤頁面。 (空白頁)。所以如果我在一秒內發出3個請求,第三個請求永遠不會檢索JSON響應。因此,loading.gif不斷轉動。

我怎麼可以讓jQuery的超時,比方說5秒,所以它會回調超時功能?

+1

'$阿賈克斯'接受'timeout'選項。然後,您可以在錯誤處理程序中測試錯誤原因(例如超時)。請查看文檔:http://api.jquery.com/jQuery.ajax/。 – 2013-02-26 02:24:23

回答

1

試試這個:

$.ajax({ 
    url: YourUrl, 
    async: true, 
    timeout: 5000,  //5 seconds 
    success: function(args) { 

        // on success code 
    } 
}) 
+0

超時後會起什麼作用?絕對不會成功:。 – 2013-02-26 02:32:20

0

您可以創建具有超時功能自定義GET請求作爲參數:

$.getWithTimeOut = function(url, params, datatype, onsuccessfunction, aftertimeoutfunction, timeout){ 
    $.get(url, params, function(data) { 
      onsuccessfunction(data); 
      setTimeout(aftertimeoutfunction, timeout); 
    }, datatype); 
}; 

然後您只要致電:

$.getWithTimeOut('url/url', { param1: value1 }, 'json', function(data){ 
    //success code here 
}, function(/*params*/){ 
    //timeout code here 
}, 5000);