如何重新发送失败的ajax请求?

hit*_*uct 12 javascript ajax jquery

我有多个ajax请求,每分钟一些请求数据由用户通过ui启动.

$.get('/myurl', data).done(function( data ){
   // do stuff..
});
Run Code Online (Sandbox Code Playgroud)

由于身份验证失败,请求可能会失败.我已经设置了一个.ajaxError()捕获任何失败请求的全局方法.

$(document).ajaxError(function( e, jqxhr ){
   // Correct error..
});
Run Code Online (Sandbox Code Playgroud)

在我发现错误后,我重置了授权.重置授权有效,但用户必须手动重新启动ajax调用(通过ui).

如何使用最初发送的jqxhr重新发送失败的请求?

(我正在使用jQuery for ajax)

Sha*_*.io 11

发现这篇文章提出了解决这个问题的好方法

主要的是使用$ .ajaxPrefilter并将自定义的错误处理程序替换为检查重试并使用闭包的'originalOptions'执行重试.

我发布代码以防万一它将来会离线,再次,信用属于原作者

// register AJAX prefilter : options, original options
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {

   originalOptions._error = originalOptions.error;

   // overwrite error handler for current request
   options.error = function( _jqXHR, _textStatus, _errorThrown ){

   if (... it should not retry ...){

         if( originalOptions._error ) originalOptions._error( _jqXHR, _textStatus, _errorThrown );
         return;
      };

      // else... Call AJAX again with original options
      $.ajax( originalOptions);
   };
});
Run Code Online (Sandbox Code Playgroud)


hvg*_*des 7

在这种情况下,我会为403状态代码编写一个特定的处理程序,这意味着未经授权(我的服务器也将返回403).从jquery ajax docs,你可以做到

$.ajax({
  statusCode: {
    403: function() {
        relogin(onSuccess);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

实现这一目标.

在该处理程序中,我将调用一个relogin方法,传递一个捕获登录成功时要执行的操作的函数.在这种情况下,您可以传入包含要再次运行的调用的方法.

在上面的代码中,relogin应该调用登录代码,并且onSuccess应该是一个包装您每分钟执行的代码的函数.

编辑 - 基于您在评论中的澄清,这种情况发生在多个请求中,我个人会为您的应用程序创建一个API,用于捕获与服务器的交互.

app = {};
app.api = {};
// now define all your requests AND request callbacks, that way you can reuse them
app.api.makeRequest1 = function(..){..} // make request 1
app.api._request1Success = function(...){...}// success handler for request 1
app.api._request1Fail = function(...){...}// general fail handler for request 1

/**
  A method that will construct a function that is intended to be executed
  on auth failure.

  @param attempted The method you were trying to execute
  @param args      The args you want to pass to the method on retry
  @return function A function that will retry the attempted method
**/
app.api.generalAuthFail = function(attempted, args){
   return function(paramsForFail){ // whatever jquery returns on fail should be the args
      if (attempted) attempted(args); 
   }  
}
Run Code Online (Sandbox Code Playgroud)

所以使用这种结构,在你的request1方法中你会做类似的事情

$().ajax({
    ....
    statusCode: {
        403: app.api.generalAuthFail(app.api.request1, someArgs);
    }
}}
Run Code Online (Sandbox Code Playgroud)

generalAuthFailure将返回执行你在传递方法的回调.