How to detect if a request was aborted?

后端 未结 4 1039
既然无缘
既然无缘 2020-12-03 02:54

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 th

相关标签:
4条回答
  • 2020-12-03 03:00

    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
    });
    
    0 讨论(0)
  • 2020-12-03 03:04

    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
        }
      }
    });
    
    0 讨论(0)
  • 2020-12-03 03:17

    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).

    0 讨论(0)
  • 2020-12-03 03:27

    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.

    0 讨论(0)
提交回复
热议问题