JQuery ambiguous ajax error

This is the gut of my ajax call.

function ajax(path, requestData, successCallBack, errorCallBack) {
    return $.ajax({
        error: function(xhr, textStatus, errorThrown) 
            Γ§(xhr, textStatus, errorThrown);
        },
        success: function(json){ 
            successCallBack(json);
        }
    });
}

When an ajax call occurs and the user clicks on the link on the page, my errorCallBack is called. A user roaming will cause the ajax call to be killed. When an error occurs on the server, the errorCallBack callback is also called.

Is there a way to differentiate the two?

Thanks!

+3
source share
4 answers

@colbeerhey's answer is good, but you can go even further. You still need to know if the server is really unavailable. I asked this question here , but the full answer is:

var running = true;
$(window).bind('beforeunload', function() { running = false; });

$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         var serverNotReached = xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0;
         if(serverNotReached && !running) 
              return;  // it not really an error, user clicked away
         else if (serverNotReached)
              // The server is down!  You didn't get any response at all.
         else
              // Do normal error handling
});

, onbeforeunload - de facto (IE FF, Webkit ), , .

+3

-, ... "" $.ajax( / ) xhr.status == 0 200/404/etc...

+1

, gnarf nickf:

jQuery , , , URL- . , ajax xmlHttpRequest:

$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) 
              return;  // it not really an error
         else
              // Do normal error handling
});
+1

xhr. HTTP.

-1

Source: https://habr.com/ru/post/1708388/


All Articles