简体   繁体   中英

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)

Is there a jQuery method to abort? or Is there a way to check if the xhr was aborted?

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 . Seems to be a jQuery 1.4+ bug. On 1.3 it called the error handler.

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.

If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method.

It may be useful to handle this (from here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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