jquery ajax的timeout參數與async參數(轉)


最近在做一個小功能的時候遇到這樣一個問題:

頁面中用ajax調用一個ws接口,有時候ws接口總是超時,我就在頁面ajax添加timeout

屬性,代碼如下:

$.ajax({ 


2     async:false, 


3     cache:false, 


4     timeout:5000, 


5     url:"someurl.htm", 


6     success:function(msg){ alert(msg); } 


7    }); 

 

加上timeout屬性后調試,發現當接口超時5秒后,頁面並未斷開請求,是timeout沒生效嗎?

查看了下timeout參數api:

Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent。

我理解的意思是:
該請求在客戶端被阻塞,就有可能在ajax sent方法被調用之前超時。按照其定義,timeout參數,應該只是請求超時,不涉及響應。 此處,服務器被阻塞,請求卻是成功了,服務器響應中。。。。。
超過設定的timeout就會執行error,單后台還在運行,只是客戶端不再做相應

修改代碼,證實一下,是否超時5秒,會執行timeout方法:

$.ajax({ 


2    async:false, 


3    cache:false, 


4    timeout:5000, 


5    url:"someurl.htm", 


6    error:function(jqXHR, textStatus, errorThrown){ 


7         alert(textStatus); 


8    }, 


9    success:function(msg){ alert(msg); } 


10   }); 

結果卻沒有alert;在網上早了一圈,結果發現async這個參數的問題,
當async設置為false,同步的時候,timeout是不生效的。

 


免責聲明!

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



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