在启动 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);
}