[jQuery] 設定 ajax() 查詢的 timeout

[jQuery] 設定 ajax() 查詢的 timeout

在用 jQuery() 提供的 ajax() 函式非同步查詢時,

有時會遇到網站沒有回應,導致 callback 一直沒有被呼叫的狀況…

 

查了一下 stackoverflow: What is jQuery’s ajax default timeout value?

原來 jQuery 的 timeout 預設值可以算是 0,

也就是沒有 timeout,實際的 timeout 要看瀏覽器而定…

 

用下面的小程式在 Chrome 裡面試跑看看…

console.log("*** ajax start:" + new Date());
$.ajax({
url: "http://1.2.3.4",
complete:   function(jqXHR, textStatus)
{
console.log("*** ajax end:" + new Date());
}
});

 

在 Chrome 44.0.2403.125 版本,測試的結果約是 75 秒,算是蠻久的~

想要修改這個 timeout 的話,可以全域修改,

或是在每個 ajax() 呼叫裡加 timeout 參數~

像我選擇的是全域修改的話,就用 ajaxSetup() 來加上 timeout:

$.ajaxSetup({
timeout: 30*1000
});

 

加上上述的設定之後,每個 ajax() 查詢最多 30 秒,

超過時間就會失敗囉~

(本頁面已被瀏覽過 3,524 次)

2 thoughts on “[jQuery] 設定 ajax() 查詢的 timeout

  1. 剛剛在Chrome Version 73.0.3 試了那段code
    結果是 1 秒
    不知我哪裡有弄錯嗎? 謝謝

    1. 要看是不是有發生什麼錯誤…
      像我假設在一個 HTTPS 網站,在 chrome developer tool console 裡,
      直接貼上那段 code,
      因為它要連的是 HTTP 網站 http://1.2.3.4,
      所以會出現 Mixed Content 的錯誤訊息:

      *** ajax start:Wed May 15 2019 11:09:36 GMT+0800 (Taipei Standard Time)
      Mixed Content: The page at ‘https://test.com’ was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ‘http://1.2.3.4/?_=1557889776440’. This request has been blocked; the content must be served over HTTPS.
      *** ajax end:Wed May 15 2019 11:09:36 GMT+0800 (Taipei Standard Time)

      如果我將 http:// 改成 https:// 就可以正確的在 30 秒後,看到 ajax end 的訊息。
      所以還是要看你遇到的錯誤訊息是什麼。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料