jQuery $.ajax calls success handler when request fails because of browser reloading

前端 未结 3 1621
小蘑菇
小蘑菇 2021-01-19 08:21

I have the following code:

 $.ajax({
          type: \"POST\",
          url: url,
          data: sendable,
          dataType: \"json\",
          success:         


        
相关标签:
3条回答
  • 2021-01-19 08:38

    You can use the onbeforeunload event on your page: link it to a function that cleans all youe AJAX requests.

    0 讨论(0)
  • 2021-01-19 08:54

    Stats strange that you are recievesing 'success' in case of failed call.. But you can try to override the behaviour, by listeining to complete event (here just a copy-paste a code from my test framework)

    $.ajax(
        {
            url: url,
            type: type,
            processData: false,
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(data),
            dataType: 'json',
            complete: function (result) {
                if (result.status == 404) {
                    ok(false, '404 error');
                } else {
                    callback($.parseJSON(result.responseText));
                }
            }
        });
    

    result is XMLHttpRequest object, so you can analyze actual status of it and decide to proceed or not proceed.

    0 讨论(0)
  • 2021-01-19 08:57

    The onbeforeunlaod technique does not work for a periodically refreshing page (for example every half seconds). I have figured out that the error caused by refreshing the page can be avoided using delaying the error handling process by a small amount of time.

    Example:

    $.ajax(...)
    .success(...)
    .error(function(jqXHR) {
    setTimeout(function() {
      // error showing process
    }, 1000);
    });
    

    In addition to that

    window.onbeforeunload = function() {//stop ajax calls}

    event can be used for less frequently refreshing ajax calls.

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