简体   繁体   English

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

[英]jQuery ajaxSetup, cannot retry ajax call into error handling

In $.ajaxSetup() I am trying to make an AJAX request after reloading a valid token if the previous token is expired. $.ajaxSetup()如果先前的令牌已过期,我试图在重载有效令牌后发出AJAX请求。 The problem is I cannot do $.ajax(this) inside the error callback. 问题是我无法在error回调内执行$.ajax(this)

 $.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 } } }); 

You could put your request inside a function then call it inside the callback again like : 您可以将请求放入函数中,然后再次在回调中调用它,如:

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
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM