gpt4 book ai didi

javascript - 在 AJAX 请求时或之后检查 Internet 连接的可靠方法?

转载 作者:行者123 更新时间:2023-11-28 06:56:22 25 4
gpt4 key购买 nike

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

我尝试过 navigator.onLine 但效果不佳。如果没有连接,它也会返回 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 errorThrown )

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

<小时/>使用 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);
}

关于javascript - 在 AJAX 请求时或之后检查 Internet 连接的可靠方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com