jQuery.ajax() - 如何处理超时最好? [英] jQuery.ajax() - How to handle timeouts best?
问题描述
我想知道,有什么处理超时是 jQuery.ajax()的最佳途径。这是我目前的解决方案:如果发生暂停的页面将重新加载和脚本得到一个机会来加载在它给的时间范围内的数据。
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.
问题:如果get_json.php(下面的例子)真的是不可用,它会成为一个无限重载循环。 可能的解决方法:添加计数器和之后$ X重载取消
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.
问题1 : 如何最好地处理超时错误?
Question 1: How to handle the timeout error best?
问2 : 你对此有何建议时限超时,为什么?
Question 2: What's your recommended timeframe for a timeout and why?
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!
推荐答案
您可以做其他的方式,可以清除间隔时首先超时发生。如果您使用此 clearInterval()
功能比你不需要重新加载页面。它会自动停止。
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.
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);
这篇关于jQuery.ajax() - 如何处理超时最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!