我使用骨干库
服务器需要每个请求的授权
因此,对服务器的任何请求都可以返回401错误
在fetch()
调用模型后如何处理401错误并使用相同选项调用fetch()
?
我在模型中使用了错误处理程序:
var Stores = Backbone.Collection.extend({
initialize: function(models, options) {
var self = this;
this.options = options;
this.on({
'error': function(model, xhr, options) {
if (xhr.status == 401) { // Not authorized
API.restoreToken(function() {
self.fetch(options);
});
}
}
});
}
});
但问题如下:当我调用self.fetch(options);
时,对象options
已经包含success
函数。
因此,self.fetch(options);
不会调用原始success
函数
答案 0 :(得分:2)
服务器需要每个请求的授权
这看起来像是一个全球性的东西所以使用$.ajaxPrefilter()
非常适合。引自
here
说明:在发送每个请求之前以及
$.ajax()
处理它们之前处理自定义Ajax选项或修改现有选项。
例如,重新设置每个ajax请求的错误函数
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
// Save original function
var originalError = options.error
// Let's hack
options.error = function(ejqXHR, textStatus, errorThrown){
if(ejqXHR.status == 401) {
API.restoreToken(function() {
//Do magic, probably reAjax with options
//Probably add anti-infinite-ajax mechanism
});
}else{
//If not 401 handle it originally
originalError(ejqXHR, textStatus, errorThrown)
}
}
}
答案 1 :(得分:0)
使用self.fetch(self.options)
;