jQuery.ajax() – 如何最好地处理超时?

我想知道,使用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); } } }); 

提前致谢!

您可以通过其他方式执行此操作,您可以在发生超时时首先清除间隔。 如果使用此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);