我想知道,使用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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
提前致谢!