How do I resend a failed ajax request?

前端 未结 4 1083
不知归路
不知归路 2020-11-27 07:20

I have multiple ajax requests some request data every minute others are initiated by the user through a ui.

$.get(\'/myurl\', data).done(function( data ){
           


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 07:38

    Found this post that suggests a good solution to this problem.

    The main thing is to use $.ajaxPrefilter and replace your error handler with a custom one that checks for retries and performs a retry by using the closure's 'originalOptions'.

    I'm posting the code just in case it will be offline in the future. Again, the credit belongs to the original author.

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

提交回复
热议问题