javascript 如何检测请求是否中止?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3648309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if a request was aborted?
提问by BrunoLM
I am making a request and then right after it I abort.
我正在提出请求,然后立即中止。
var x = $.get(url, function (d, e, xhr) { alert(d); });
x.abort();
The problem is that it executes the successfunction and returns empty data... (example here)
问题是它执行success函数并返回空数据...... (示例here)
Is there a jQuery method to abort? or Is there a way to check if the xhrwas aborted?
是否有一个 jQuery 方法可以中止?或者有没有办法检查是否xhr中止?
采纳答案by BrunoLM
回答by fabdouglas
The best way to detect request abortion and avoiding false positive from offline mode :
检测请求中止和避免离线模式误报的最佳方法:
$("#loading").ajaxError(function(event, xhr) {
if (xhr.status === 0) {
if (xhr.statusText === 'abort') {
// Has been aborted
} else {
// Offline mode
}
}
});
回答by user113716
EDIT:Try this:
编辑:试试这个:
x.onreadystatechange = null;
x.abort();
Seems to work. Not sure what side effects, if any.
似乎工作。不知道有什么副作用,如果有的话。
Original answer:
原答案:
Would it be sufficient to just test the response received?
仅测试收到的响应就足够了吗?
var x = $.get("./", function (d, e, xhr) {
if(d) {
// run your code with response
alert(d);
}
// otherwise, nothing will happen
});
回答by Codesleuth
This is by design. Test if datais null to determine if the request responded correctly.
这是设计使然。测试是否data为空以确定请求是否正确响应。
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global
.ajaxError()method.
如果使用 jQuery.get() 的请求返回错误代码,它将静默失败,除非脚本也调用了全局
.ajaxError()方法。
It may be useful to handle this (from here).
处理这个可能有用(从这里)。

