javascript 如何重新发送失败的 ajax 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8881614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I resend a failed ajax request?
提问by hitautodestruct
I have multiple ajax requests some request data every minute others are initiated by the user through a ui.
我每分钟有多个 ajax 请求一些请求数据,其他请求数据由用户通过 ui 发起。
$.get('/myurl', data).done(function( data ){
// do stuff..
});
The request might fail due to an authentication failure.
I've setup a global .ajaxError()
method for catching any failed requests.
由于身份验证失败,请求可能会失败。我已经设置了一个全局.ajaxError()
方法来捕获任何失败的请求。
$(document).ajaxError(function( e, jqxhr ){
// Correct error..
});
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).
在我发现错误后,我重置了授权。重置授权有效,但用户必须手动重新启动 ajax 调用(通过 ui)。
How do I resend the failed request using the jqxhr originally sent?
如何使用最初发送的 jqxhr 重新发送失败的请求?
(I'm using jQuery for the ajax)
(我为 ajax 使用 jQuery)
采纳答案by Shai Reznik - HiRez.io
Found this postthat suggests a good solution to this problem.
发现这篇文章提出了解决这个问题的好方法。
The main thing is to use $.ajaxPrefilterand replace your error handler with a custom one that checks for retries and performs a retry by using the closure's 'originalOptions'.
主要的是使用$.ajaxPrefilter并用自定义的错误处理程序替换您的错误处理程序,该处理程序检查重试并使用闭包的“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);
};
});
回答by hvgotcodes
In this case, I would write a specific handler for the 403
status code, which means unauthorized (my server would return a 403 too). From the jquery ajax docs, you can do
在这种情况下,我将为403
状态代码编写一个特定的处理程序,这意味着未经授权(我的服务器也会返回 403)。从 jquery ajax 文档,你可以做
$.ajax({
statusCode: {
403: function() {
relogin(onSuccess);
}
}
});
to achieve that.
实现这一目标。
In that handler, I would call a relogin
method, passing a function that captures what to do when login succeeds. In this case, you could pass in the method that contains the call you want to run again.
在那个处理程序中,我会调用一个relogin
方法,传递一个函数来捕获登录成功时要执行的操作。在这种情况下,您可以传入包含要再次运行的调用的方法。
In the code above, relogin
should call the login code, and onSuccess
should be a function that wraps the code you execute every minute.
在上面的代码中,relogin
应该调用登录代码,并且onSuccess
应该是一个包装你每分钟执行一次的代码的函数。
EDIT- based on your clarification in comment, that this scenario happens for multiple requests, I personally would create an API for your app that captures the interactions with the server.
编辑 - 根据您在评论中的澄清,这种情况发生在多个请求中,我个人会为您的应用程序创建一个 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);
}
}
so with that structure, in your request1
method you would do something like
所以使用这种结构,在你的request1
方法中你会做类似的事情
$().ajax({
....
statusCode: {
403: app.api.generalAuthFail(app.api.request1, someArgs);
}
}}
the generalAuthFailure
will return a callback that executes the method you pass in.
在generalAuthFailure
将返回执行你在传递方法的回调。
回答by Sabri Aziri
The code below will keep the original request and it will try to success 3 times.
下面的代码将保留原始请求并尝试成功 3 次。
var tries = 0;
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if(tries < 3){
tries++;
$.ajax(this).done(function(){tries=0;});
}
});
回答by hitautodestruct
You could possibly go by the option of naming each one of your functions and then recalling them as stated in hvgotcodes' answers.
您可以选择命名您的每个函数,然后按照 hvgotcodes 的答案中的说明调用它们。
Or
或者
You can use a reusable function to setup a request while extending the defaults:
您可以使用可重用函数来设置请求,同时扩展默认值:
function getRequest( options ){
var // always get json
defaults = { dataType: 'json' },
settings = $.extend( defaults, options );
return // send initial ajax, if it's all good return the jqxhr object
$.ajax( settings )
// on error
.fail(function( jqxhr, e ){
// if the users autherization has failed out server responds with a 401
if( jqxhr.status === 401 ){
// Authenticate user again
resetAuthentication()
.done(function(){
// resend original ajax also triggering initial callback
$.ajax( settings );
});
}
});
};
To use the above function you would write something like this:
要使用上述函数,您可以编写如下内容:
getRequest({
url: 'http://www.example.com/auth.php',
data: {user: 'Mike', pass: '12345'},
success: function(){ // do stuff }
});
The getRequest()
could probably be made recursive and/or converted into a jQuery plugin but this was sufficient for my needs.
将getRequest()
很可能进行递归和/或转换成一个jQuery插件,但这足以满足我的需求。
Note:If the resetAutentication function might faile, getRequest()
would have to be recursive.
注意:如果 resetAutentication 函数可能失败,getRequest()
则必须递归。