【问题标题】:Reliable way to check the Internet connection for or after an AJAX requests?在 AJAX 请求之后或之后检查 Internet 连接的可靠方法?
【发布时间】:2015-09-12 06:29:08
【问题描述】:

有没有办法在 AJAX 请求之前检查 Internet 连接或在操作之后获取错误代码?它应该使用 Javascript 或 JQuery 进行测试。

我尝试过 navigator.onLine 效果不佳。如果没有连接,它也会返回 true。

【问题讨论】:

  • 我会尝试向您知道已启动的站点(即 Google 服务)发送请求,然后从中读取返回的状态代码。
  • 如果您在客户端 LAN 之外的服务器上提供页面,那么他们很可能在线
  • 没有可靠的方法。例如,从另一个站点请求首先确定该站点是否响应您。如果没有,这是否意味着... a) 没有互联网连接,b) 该站点已关闭,或 c) 该站点已启动但未响应您的请求(临时故障?)所以,有一切机会你可能会得到一个假阴性
  • 处理失败的最佳错误代码是什么?
  • 错误码是什么意思?

标签: javascript jquery connection


【解决方案1】:

在启动 AJAX 请求之前不知道如何处理这个问题。这是在jQuery.ajax 中使用.error 实现相同目的的另一种方法。伪代码

var timeInterval = 5000,
    step = 1,
    timeOutID;

function DoSomething() {
    $.ajax({
        //...
        timeout: 5000;
        //...
    }).done(function (data) {
        step = 1; // reset delay
        //process your data
    }).error(function (xhr, status, error) {
        //Houston in the blind!
        if (status == "timeout") {
            if (timeOutID) window.clearTimeout(timeOutID);
            timeoutID = window.setTimeout(function () {
                DoSomething();
            }, (timeInterval * step++)); //to increase delay on each consecutive call
        }
    });
}

因为根据 jQuery 文档,我们有一个 textStatus == "timeout"

错误类型:函数(jqXHR jqXHR,字符串 textStatus,字符串 错误抛出)

请求失败时调用的函数。函数接收 三个参数:jqXHR(在 jQuery 1.4.x 中,XMLHttpRequest)对象,一个 描述发生的错误类型和可选的字符串 异常对象,如果发生。第二个可能的值 参数(除了null)是"timeout""error""abort""parsererror"。当发生 HTTP 错误时,errorThrown 会收到 HTTP 状态的文本部分,例如“未找到”或“内部” 服务器错误。”


使用香草 JS
var timeInterval = 5000,
    step = 1,
    timeOutID;

function DoSomething() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            step = 1; // reset delay
            //process your data
        }
    };

    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xhr.timeout = 5000; // this is not our variable "timeInterval", its the request timeout
    xhr.ontimeout = function () {
        if (timeOutID) window.clearTimeout(timeOutID);
        timeoutID = window.setTimeout(function () {
            DoSomething();
        }, (timeInterval * step++));
    }
    xhr.send(json);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多