【发布时间】:2013-06-13 22:15:01
【问题描述】:
我想知道,用 jQuery.ajax() 处理超时的最佳方法是什么。这就是我目前的解决方案:如果发生超时,页面将被重新加载,并且脚本有另一个机会在给定的时间范围内加载数据。
问题:如果“get_json.php”(下面的示例)真的不可用,它将成为一个无限的重新加载循环。 可能的解决方案:添加一个计数器并在 $x 重新加载后取消。
问题 1: 如何最好地处理超时错误?
问题 2: 您建议的超时时间范围是什么?为什么?
代码:
$.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);
}
}
});
提前致谢!
【问题讨论】:
-
为什么要重新加载整个页面而不是重试 Ajax 调用?
-
@Juhana:你的意思是 $.ajax(this); ?
-
嗯,是的,例如。
-
@Juhana:简单而伟大,谢谢!
标签: javascript jquery ajax error-handling timeout