jQuery ajaxSetup, не может повторить вызов ajax в обработку ошибок - PullRequest
0 голосов
/ 28 ноября 2018

В $.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 голосов
/ 28 ноября 2018

Вы можете поместить свой запрос в функцию, а затем снова вызвать ее внутри обратного вызова, например:

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
    }
  }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...