我怎么能拦截事件处理程序之前在jQuery的Ajax响应? [英] How can I intercept ajax responses in jQuery before the event handler?
问题描述
我想注册一个全球性的事件处理程序,所有的AJAX请求,这样我可以从服务器截获并处理响应的具体的事件处理程序得到他们之前的。
I'd like to register a global event handler for all AJAX requests, so that I can intercept and handle responses from the server before the specific event handler gets them.
例如,我的code可能是这样的:
For example, my code might have something like:
$("#placeholder").load("/fragments/userpics");
和我想注册一个事件之前的处理程序,这样我可以,例如,如果返回一个401响应显示一个登录框,或者重试,如果有一个503的响应。
And I'd like to register a "before" event handler so that I could, for example, display a login box if a 401 response is returned, or maybe retry if there's a 503 response.
我觉得 $。ajaxError()
是我的事件处理程序后,会做这样的事情,但显然它只是引发
I thought that $.ajaxError()
is where I would do something like this, but apparently it is only triggered after the event handler.
更新:好吧,这里是我到目前为止,与@genesis的帮助:
UPDATE: OK, here's what I got so far, with the help of @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);
};
});
做了一些测试后,它看起来像我还需要重写 options.complete
。
然而,这仍然没有涵盖所有的基础,因为你也可以直接将事件附加到jqXHR对象,并更改选项
将不会在这种情况下帮助
However, this still doesn't cover all the bases, since you can also attach events directly to the jqXHR object, and changing options
won't help in this case.
任何提示?
推荐答案
如果你想处理即将从服务器返回的事件处理程序之前的数据,使用datafilter:
If you want to handle the data coming back from the server before the event handler, use datafilter:
jquery.ajaxSetup({
dataFilter: function (data, type) {
//modify the data
return data;
}
});
这篇关于我怎么能拦截事件处理程序之前在jQuery的Ajax响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!