可靠的方式来检查互联网连接或AJAX请求之后

Reliable way to check the Internet connection for or after an AJAX requests?

本文关键字:连接 AJAX 请求 之后 互联网 检查 方式      更新时间:2023-09-26

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

我试过导航器。在线,但效果不好。如果没有连接,它也返回true。

在开始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"

error Type: Function(jqXHR jqXHR, String textStatus, String . error错误抛出)

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


使用Vanilla 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);
}