Jquery Ajax error handling to ignore aborted

后端 未结 9 711
栀梦
栀梦 2020-12-07 17:35

I want to have a global error handling method for ajax calls, this is what I have now:

$.ajaxSetup({
  error: function (XMLHttpRequest, textStatus, errorThro         


        
相关标签:
9条回答
  • 2020-12-07 17:58

    You'll want to look at the textStatus argument passed into your error function. According to http://api.jquery.com/jQuery.ajax/, it can take the values "success", "notmodified", "error", "timeout", "abort", or "parsererror". "abort" is obviously what you want to check against.

    Longer notes here: jquery-gotcha-error-callback-triggered-on-xhr-abort

    0 讨论(0)
  • 2020-12-07 18:07
    $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    
        if (!jqXHR.getAllResponseHeaders()) {
            return;
        }           
    }); 
    
    0 讨论(0)
  • 2020-12-07 18:11

    Something I found is that when there is an aborted request, the status and/or readyState equal 0.

    In my global error handler, I have a check at the top of the method:

    $(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
        //If either of these are true, then it's not a true error and we don't care
        if (jqXHR.status === 0 || jqXHR.readyState === 0) {
            return;
        }
    
        //Do Stuff Here
    });
    

    I've found this works perfectly for me. Hope this helps you, or anyone else who runs into this :)

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