javascript jQuery.ajax() - 如何最好地处理超时?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17156332/
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
jQuery.ajax() - How to handle timeouts best?
提问by Mr. B.
I'm wondering, what's the best way to handle timeouts with jQuery.ajax(). That's my solution at the moment: If an timeout occurs the page will be reloaded and the script gets another chance to load the data within it's given timeframe.
我想知道,使用jQuery.ajax()处理超时的最佳方法是什么。这就是我目前的解决方案:如果发生超时,页面将被重新加载,并且脚本有另一个机会在给定的时间范围内加载数据。
Problem: if "get_json.php" (example below) is really not available, it will become an endless reloading-loop. Possible solution: adding a counter and cancel after $x reloads.
问题:如果“get_json.php”(下面的例子)真的不可用,它将成为一个无休止的重新加载循环。可能的解决方案:添加一个计数器并在 $x 重新加载后取消。
Question 1: How to handle the timeout error best?
问题 1:如何最好地处理超时错误?
Question 2: What's your recommended timeframe for a timeout and why?
问题 2:您建议的暂停时间范围是多少?为什么?
Code:
代码:
$.ajax({
type: "POST",
url: "get_json.php",
timeout: 500,
dataType: "json",
success: function(json) {
alert("JSON loaded: " + json);
},
error: function(request, status, err) {
if (status == "timeout") {
// timeout -> reload the page and try again
console.log("timeout");
window.location.reload();
} else {
// another error occured
alert("error: " + request + status + err);
}
}
});
Thanks in advance!
提前致谢!
采纳答案by Ghanshyam Katriya
You can do it other way, you can clear interval first when timeout occured. If you use this clearInterval()
function than you won't need to reload page. It'll stop automatically.
您可以通过其他方式做到这一点,您可以在超时发生时先清除间隔。如果您使用此clearInterval()
功能,则不需要重新加载页面。它会自动停止。
function ajax_call(){
$.ajax({
type: "POST",
url: "get_json.php",
timeout: 500,
dataType: "json",
success: function(json) {
alert("JSON loaded: " + json);
},
error: function(request, status, err) {
if (status == "timeout") {
// timeout -> reload the page and try again
clearInterval(ajax_call);
window.location.reload(); //make it comment if you don't want to reload page
} else {
// another error occured
alert("error: " + request + status + err);
}
}
});
}
setInterval(ajax_call,timeout_duration);