我如何重新发送失败ajax请求? [英] How do I resend a failed ajax request?
问题描述
我有多个AJAX请求每分钟另一些由用户发起的一些请求数据通过一个用户界面。
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 ){
// do stuff..
});
请求可能会因身份验证失败失败。
我设置一个全球性的 .ajaxError()
方法捕获任何失败的请求。
The request might fail due to an authentication failure.
I've setup a global .ajaxError()
method for catching any failed requests.
$(document).ajaxError(function( e, jqxhr ){
// Correct error..
});
在我捕获错误我重新授权。 重新授权工作,但用户必须手动重新启动Ajax调用(通过用户界面)。
After I catch the error I reset authorization. Resetting the authorization works but the user has to manually re initiate the ajax call (through the ui).
我如何重新发送失败请求使用最初发送jqxhr?
How do I resend the failed request using the jqxhr originally sent?
(我使用jQuery的AJAX)
(I'm using jQuery for the ajax)
推荐答案
找到这篇文章这提出了一个很好的解决了这个问题。
Found this post that suggests a good solution to this problem
最主要的是使用$阿贾克斯prefilter和一个自定义的一个检查重试更换你的错误处理程序,并通过使用封闭的originalOptions进行重试。
The main thing is to use $.ajaxPrefilter and replace your error handler with a custom one that checks for retries and perform a retry by using the closure's 'originalOptions'.
我张贴了code,以防万一这将是离线的未来,再次,信贷所属的原作者
I'm posting the code just in case it will be offline in the future, again, the credit belongs to the original writer
// 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);
};
});
这篇关于我如何重新发送失败ajax请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!