javascript 如何设置ajax超时?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7280093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set up ajax time out?
提问by buzz3110
I have this code to time out ajax call after 40 secs:
我有这个代码在 40 秒后超时 ajax 调用:
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true); xmlhttp.onreadystatechange = showResults;
xmlhttp.send(null);
var httpTimeOut=setTimeout("ajaxTimeout();",40000);
}
function ajaxTimeout() {
xmlhttp.abort();
document.getElementById('errorShow').innerHTML = "Request Timed out";
}
However I am unable to test this due to environment constraints at my place. Can anyone please tell if this is correct or any modifications are required??
但是,由于我所在的环境限制,我无法对此进行测试。谁能告诉我这是正确的还是需要任何修改?
回答by Nemoden
Should fix that:
应该解决这个问题:
if (xmlhttp) {
xmlhttp.open("GET", MY_SERVLET, true);
xmlhttp.onreadystatechange = showResults;
xmlhttp.send(null);
setTimeout(function() { xmlhttp.abort() },40000);
since ajaxTimeout
function can't "see" xmlhttp
variable, but we can use anonymous function to have access to local variables.
由于ajaxTimeout
函数不能“看到”xmlhttp
变量,但我们可以使用匿名函数来访问局部变量。
Yet another approach is to use jQuery.ajax
so the library would take care of it.
另一种方法是使用,jQuery.ajax
以便图书馆处理它。
Your code would look like so:
您的代码如下所示:
$.ajax({
url: MY_SERVLET,
async: true,
timeout: 40000,
success: function(args) {
// on success code
}
})