在这种情况下,我将为403
状态代码编写一个特定的处理程序,这意味着未经授权(我的服务器也会返回 403)。从 jquery ajax 文档,你可以做
$.ajax({
statusCode: {
403: function() {
relogin(onSuccess);
}
}
});
实现这一目标。
在那个处理程序中,我会调用一个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);
}
}
所以使用这种结构,在你的request1
方法中你会做类似的事情
$().ajax({
....
statusCode: {
403: app.api.generalAuthFail(app.api.request1, someArgs);
}
}}
在generalAuthFailure
将返回执行你在传递方法的回调。