使用jQuery重试失败的 AJAX 请求的最佳方法是什么?

63lcw9qa  于 2023-01-04  发布在  jQuery
关注(0)|答案(9)|浏览(98)

伪码:

$(document).ajaxError(function(e, xhr, options, error) {
  xhr.retry()
})

更好的是某种指数回退

ss2ws0br

ss2ws0br1#

大概是这样的

$.ajax({
    url : 'someurl',
    type : 'POST',
    data :  ....,   
    tryCount : 0,
    retryLimit : 3,
    success : function(json) {
        //do something
    },
    error : function(xhr, textStatus, errorThrown ) {
        if (textStatus == 'timeout') {
            this.tryCount++;
            if (this.tryCount <= this.retryLimit) {
                //try again
                $.ajax(this);
                return;
            }            
            return;
        }
        if (xhr.status == 500) {
            //handle error
        } else {
            //handle error
        }
    }
});
hof1towb

hof1towb2#

一种方法是使用 Package 函数:

(function runAjax(retries, delay){
  delay = delay || 1000;
  $.ajax({
    type        : 'GET',
    url         : '',
    dataType    : 'json',
    contentType : 'application/json'
  })
  .fail(function(){
    console.log(retries); // prrint retry count
    retries > 0 && setTimeout(function(){
        runAjax(--retries);
    },delay);
  })
})(3, 100);

另一种方法是在$.ajax上使用retries属性

// define ajax settings
var ajaxSettings = {
  type        : 'GET',
  url         : '',
  dataType    : 'json',
  contentType : 'application/json',
  retries     : 3  //                 <-----------------------
};

// run initial ajax
$.ajax(ajaxSettings).fail(onFail)

// on fail, retry by creating a new Ajax deferred
function onFail(){
  if( ajaxSettings.retries-- > 0 )
    setTimeout(function(){
        $.ajax(ajaxSettings).fail(onFail);
    }, 1000);
}

另一种方式(GIST)-覆盖原始$.ajax(更适合DRY)

// enhance the original "$.ajax" with a retry mechanism 
$.ajax = (($oldAjax) => {
  // on fail, retry by creating a new Ajax deferred
  function check(a,b,c){
    var shouldRetry = b != 'success' && b != 'parsererror';
    if( shouldRetry && --this.retries > 0 )
      setTimeout(() => { $.ajax(this) }, this.retryInterval || 100);
  }

  return settings => $oldAjax(settings).always(check)
})($.ajax);


// now we can use the "retries" property if we need to retry on fail
$.ajax({
    type          : 'GET',
    url           : 'http://www.whatever123.gov',
    timeout       : 2000,
    retries       : 3,     //       <-------- Optional
    retryInterval : 2000   //       <-------- Optional
})
// Problem: "fail" will only be called once, and not for each retry
.fail(()=>{
  console.log('failed') 
});

要考虑的一点是确保$.ajax方法之前没有 Package ,以避免相同的代码运行两次。
您可以将这些代码段(按原样)复制粘贴到控制台以进行测试

xcitsw88

xcitsw883#

我已经用下面的代码取得了很大的成功(例如:http://jsfiddle.net/uZSFK/

$.ajaxSetup({
    timeout: 3000, 
    retryAfter:7000
});

function func( param ){
    $.ajax( 'http://www.example.com/' )
        .success( function() {
            console.log( 'Ajax request worked' );
        })
        .error(function() {
            console.log( 'Ajax request failed...' );
            setTimeout ( function(){ func( param ) }, $.ajaxSetup().retryAfter );
        });
}
bq9c1y66

bq9c1y664#

如果有人在 AJAX 调用之后调用.done(),这些答案都不起作用,因为你没有success方法来附加到将来的回调中。

$.ajax({...someoptions...}).done(mySuccessFunc);

那么mySuccessFunc不会在重试时被调用。下面是我的解决方案,它大量借用了@cjpak的答案here。在我的例子中,我希望在AWS的API网关响应502错误时重试。

const RETRY_WAIT = [10 * 1000, 5 * 1000, 2 * 1000];

// This is what tells JQuery to retry $.ajax requests
// Ideas for this borrowed from https://stackoverflow.com/a/12446363/491553
$.ajaxPrefilter(function(opts, originalOpts, jqXHR) {
  if(opts.retryCount === undefined) {
    opts.retryCount = 3;
  }

  // Our own deferred object to handle done/fail callbacks
  let dfd = $.Deferred();

  // If the request works, return normally
  jqXHR.done(dfd.resolve);

  // If the request fails, retry a few times, yet still resolve
  jqXHR.fail((xhr, textStatus, errorThrown) => {
    console.log("Caught error: " + JSON.stringify(xhr) + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
    if (xhr && xhr.readyState === 0 && xhr.status === 0 && xhr.statusText === "error") {
      // API Gateway gave up.  Let's retry.
      if (opts.retryCount-- > 0) {
        let retryWait = RETRY_WAIT[opts.retryCount];
        console.log("Retrying after waiting " + retryWait + " ms...");
        setTimeout(() => {
          // Retry with a copied originalOpts with retryCount.
          let newOpts = $.extend({}, originalOpts, {
            retryCount: opts.retryCount
          });
          $.ajax(newOpts).done(dfd.resolve);
        }, retryWait);
      } else {
        alert("Cannot reach the server.  Please check your internet connection and then try again.");
      }
    } else {
      defaultFailFunction(xhr, textStatus, errorThrown); // or you could call dfd.reject if your users call $.ajax().fail()
    }
  });

  // NOW override the jqXHR's promise functions with our deferred
  return dfd.promise(jqXHR);
});

这个代码段将在2秒、5秒、10秒后回退并重试,您可以通过修改RETRY_WAIT常量来编辑这一点。
AWS支持建议我们添加重试,因为它对我们来说只有一次。

kfgdxczn

kfgdxczn5#

您的代码几乎已满:)

const counter = 0;
$(document).ajaxSuccess(function ( event, xhr, settings ) {
    counter = 0;
}).ajaxError(function ( event, jqxhr, settings, thrownError ) {
    if (counter === 0 /*any thing else you want to check ie && jqxhr.status === 401*/) {
        ++counter;
        $.ajax(settings);
    }
});
oxcyiej7

oxcyiej76#

下面是一个小插件:
https://github.com/execjosh/jquery-ajax-retry
自动增加超时将是一个很好的补充。
要在全球范围内使用它,只需创建您自己的带有$. AJAX 签名的函数,使用there retry API并将所有$.ajax调用替换为新函数。
你也可以直接替换$. AJAX ,但是如果不重试,你将无法调用xhr。

93ze6v8z

93ze6v8z7#

下面是我异步加载库的方法:

var jqOnError = function(xhr, textStatus, errorThrown ) {
    if (typeof this.tryCount !== "number") {
      this.tryCount = 1;
    }
    if (textStatus === 'timeout') {
      if (this.tryCount < 3) {  /* hardcoded number */
        this.tryCount++;
        //try again
        $.ajax(this);
        return;
      }
      return;
    }
    if (xhr.status === 500) {
        //handle error
    } else {
        //handle error
    }
};

jQuery.loadScript = function (name, url, callback) {
  if(jQuery[name]){
    callback;
  } else {
    jQuery.ajax({
      name: name,
      url: url,
      dataType: 'script',
      success: callback,
      async: true,
      timeout: 5000, /* hardcoded number (5 sec) */
      error : jqOnError
    });
  }
}

然后,只需从应用调用.load_script并嵌套成功回调即可:

$.loadScript('maps', '//maps.google.com/maps/api/js?v=3.23&libraries=geometry&libraries=places&language=&hl=&region=', function(){
    initialize_map();
    loadListeners();
});
rjjhvcjd

rjjhvcjd8#

DemoUsers的答案在Zepto中不起作用,因为error函数中的this指向Window(使用'this'的方式不够安全,因为你不知道他们是如何实现 AJAX 的,或者没有必要知道)。
对于Zepto,也许你可以试试下面的,到目前为止,它对我来说效果很好:

var AjaxRetry = function(retryLimit) {
  this.retryLimit = typeof retryLimit === 'number' ? retryLimit : 0;
  this.tryCount = 0;
  this.params = null;
};
AjaxRetry.prototype.request = function(params, errorCallback) {
  this.tryCount = 0;
  var self = this;
  params.error = function(xhr, textStatus, error) {
    if (textStatus === 'timeout') {
      self.tryCount ++;
      if (self.tryCount <= self.retryLimit) {
        $.ajax(self.params)      
        return;
      }
    }
    errorCallback && errorCallback(xhr, textStatus, error);
  };
  this.params = params;
  $.ajax(this.params);
};
//send an ajax request
new AjaxRetry(2).request(params, function(){});

使用构造函数来确保请求是可重入的!

xggvc2p6

xggvc2p69#

我用@vsync第三个代码解决了我的具体问题。

$.ajax = (($oldAjax) => {
    
  var df = $.Deferred();
  
  // on fail, retry by creating a new Ajax deferred
  function check(self, status) {
    console.log("check " + status + " => " + self.retries);
    const shouldRetry = status != 'success' && status != 'parsererror';
    if (shouldRetry && self.retries > 0) {
      setTimeout(() => {
        console.log("retry " + self.retries);
        $.ajax(self);
      }, self.retryInterval || 100);
    }
  }

  function failed(jqXHR, status, e) {
    if (this.retries - 1 <= 0) {
      // 재시도 횟수가 끝나면, 오류 보내기
      df.reject(KfError.convertKfError(jqXHR, this.url));
    } else {
      this.retries --;
      check(this, 'retry', this.retries);
    }
  }

  function done(res, textStatus, jqXHR) {
    if (!res.success) { // 200 코드이지만, 응답에 실패라면 오류로 처리
      if (this.retries - 1 <= 0) {
        df.reject(KfError.createResponseError(res, this.url));
      } else {
        this.retries --;
        check(this, 'retry', this.retries)
      }
    } else {
      df.resolve(res, textStatus, jqXHR);
    }
  }
  return function (settings) {
    $oldAjax(settings)
      .fail(failed)
      .done(done);
    return df;
  };
})($.ajax);

function createRequest(url) {
  return $.ajax({
    type: 'GET',
    url: url,
    timeout: 2000,
    retries: 3,
    retryInterval: 1000
  });
}

$(function () {
  createRequest(Rest.correctUrl('/auth/refres'))
    .then((res) => {
      console.log('ok res');
    })
    .catch((e) => {
      // Finally catch error after retrial.
      console.log(e);
    });
});

相关问题