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