【问题标题】:jQuery.ajax() - How to handle timeouts best?jQuery.ajax() - 如何最好地处理超时?
【发布时间】: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


【解决方案1】:

你可以用其他方式,当超时发生时你可以先清除间隔。如果您使用此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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2014-01-28
    • 2010-09-06
    • 2021-06-16
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多