我想为所有AJAX请求注册一个全局事件处理程序,这样我就可以在特定事件处理程序获取之前拦截并处理来自服务器的响应.
例如,我的代码可能包含以下内容:
$("#placeholder").load("/fragments/userpics");
Run Code Online (Sandbox Code Playgroud)
我想注册一个"之前"事件处理程序,以便我可以,例如,如果返回401响应,则显示一个登录框,或者如果有503响应则可以重试.
我认为这$.ajaxError()
是我会做这样的事情,但显然它只是在事件处理程序之后触发.
更新:好的,这是我迄今为止得到的,在@genesis的帮助下:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
var success = options.success;
options.success = function(data, textStatus, jqXHR) {
// override success handling
if(typeof(success) === "function") return success(data, textStatus, jqXHR);
};
var error = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
// override error handling
if(typeof(error) === "function") return error(jqXHR, textStatus, errorThrown);
};
});
Run Code Online (Sandbox Code Playgroud)
做了一些测试之后,看起来我还需要覆盖options.complete
.
但是,这仍然没有涵盖所有基础,因为您还可以将事件直接附加到jqXHR对象,options
在这种情况下更改将无济于事.
有小费吗?
Hug*_*rte 19
如果要在事件处理程序之前处理从服务器返回的数据,请使用datafilter:
jQuery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});
Run Code Online (Sandbox Code Playgroud)
在发送每个请求之前以及$ .ajax()处理它们之前,处理自定义Ajax选项或修改现有选项.
http://api.jquery.com/jQuery.ajaxPrefilter/
我打赌它也适用于.load()
归档时间: |
|
查看次数: |
16162 次 |
最近记录: |