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!
提前致谢!
1 个解决方案
#1
4
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);
#1
4
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);