jQuery ajaxSetup,无法重试对错误处理的ajax调用

时间:2018-11-28 16:07:07

标签: javascript jquery ajax

$.ajaxSetup()中,如果先前的令牌已过期,我试图在重载有效令牌后发出AJAX请求。问题是我无法在$.ajax(this)回调中执行error

$.ajax({
  url: _url
  //async: false,
  type: 'POST'
}).success(function(jsonP) {
  // ...
}).error(
  // ...
);

$.ajaxSetup({
  tryCount: 0,
  retryLimit: 2,
  error: function(xhr, textStatus, errorThrown) {
    if (xhr.status == 401 && (JSON.parse(localStorage.getItem('Auth')).user[0] != null)) {
      refreshToken();
      this.tryCount++;
      setTimeout(function() {
        console.log(xhr);
        if (this.tryCount <= this.retryLimit) { // this.tryCount is undefined
          //try again
          $.ajax(this); // the problem is here : how to call the request again !
          $('#loading-modal').modal('hide');
          return;
        } else {
          alert("Problème de connexion");
          return false;
        }
      }, 1000);
      return;
    } else {
      /* alert("Problème d'authentification");
      $(".logout").trigger('click'); */
    }
    if (xhr.status == 500) {
      //handle error
    } else {
      //handle error
    }
  }
});

1 个答案:

答案 0 :(得分:0)

您可以将请求放入函数中,然后再次在回调中调用它,如:

function myRequest(){
    $.ajax({
      url: _url
      //async: false,
      type: 'POST'
    }).success(function(jsonP) {
      // ...
    }).error(
      // ...
    );
}

myRequest();

$.ajaxSetup({
  tryCount: 0,
  retryLimit: 2,
  error: function(xhr, textStatus, errorThrown) {
    if (xhr.status == 401 && (JSON.parse(localStorage.getItem('Auth')).user[0] != null)) {
      refreshToken();
      this.tryCount++;
      setTimeout(function() {
        console.log(xhr);
        if (this.tryCount <= this.retryLimit) { // this.tryCount is undefined
          //try again
          myRequest();

          $('#loading-modal').modal('hide');
          return;
        } else {
          alert("Problème de connexion");
          return false;
        }
      }, 1000);
      return;
    } else {
      /* alert("Problème d'authentification");
      $(".logout").trigger('click'); */
    }
    if (xhr.status == 500) {
      //handle error
    } else {
      //handle error
    }
  }
});