简体   繁体   English

如何检测请求是否中止?

[英]How to detect if a request was aborted?

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 success function and returns empty data... (example here) 问题是它执行success函数并返回空数据... (例如这里)

Is there a jQuery method to abort? 是否有一个jQuery方法可以中止? or Is there a way to check if the xhr was aborted? 或者有没有办法检查xhr是否中止?

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
    }
  }
});

I found here that the xhr will return with status 0 . 我在这里发现xhr将以状态0返回。 Seems to be a jQuery 1.4+ bug. 似乎是一个jQuery 1.4+错误。 On 1.3 it called the error handler. 在1.3上它称为错误处理程序。

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
});

This is by design. 这是设计的。 Test if data is null to determine if the request responded correctly. 测试data是否为null以确定请求是否正确响应。

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 ). 处理这个问题可能很有用(从这里开始 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM