这是一个典型的Ajax通话看起来像我:
$.ajax({
type: "POST",url: "someURL"
data: "someDataString",beforeSend: function(msg){
$(".button").button("disable");
},success: function(msg){
$(".button").button("enable");
// some user Feedback
}
});
但我不要添加这个按钮 – 禁用每个Ajax调用中的逻辑。有没有办法全局定义一个函数,每次前/后和ajax调用调用?
解决方法
对于jQuery 1.5和更高版本
init之后添加多个回调
由于jQuery 1.5,您可以添加多个回调感谢大修的API和新引入的jqXHR对象,由.ajax返回。它实现了Promise(见Deferreds)接口,我们可以使用它来获得我们的优势:
// fn to handle button-toggling
var toggleButton = function() {
var button = $(".button");
button.button(button.button("option","disabled") ? "enable" : "disable");
}
// store returned jqXHR object in a var so we can reference to it
var req = $.ajax({
beforeSend: toggleButton,success: function(msg){
/* Do what you want */
}
}).success(toggleButton);
// we can add even more callbacks
req.success(function(){ ... });
使用预过滤器
jQuery 1.5还引入了prefilters,您可以使用它来替换jQuery 1.4的全局配置:
// good practice: don't repeat yourself,especially selectors
var button = $(".button");
$.ajaxPrefilter(function(options,_,jqXHR) {
button.button("disable");
jqXHR.complete(function() {
button.button("enable");
});
});
注意:jqXHR section of the $.ajax entry有关于使用jqXHR.success()的通知:
Deprecation Notice: The jqXHR.success(),jqXHR.error(),and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal,use jqXHR.done(),jqXHR.fail(),
and jqXHR.always() instead.
对于jQuery 1.4和更早版本
事件和全局配置
使用.ajaxStart和.ajaxStop将回调绑定到特定的选择器。触发这些回调的事件将在所有Ajax请求上触发。
$(".button").ajaxStart(function(){
$(this).button("disable");
}).ajaxStop(function(){
$(this).button("enable");
});
使用.ajaxSetup设置全局ajax配置。传递给.ajaxSetup的设置对象将应用于所有Ajax请求,即使是由shorthands .get,.getJSON和.post生成的请求。注意,这不推荐,因为它可以轻易地破坏其功能。
$.ajaxSetup({
beforeSend: function(){
$(".button").button("disable");
},success: function(){
$(".button").button("enable");
}
});
在全局事件回调中过滤出请求
如果你需要过滤掉某些请求,你可以使用.ajaxSend和.ajaxComplete,你可以检查Ajax设置对象。这样的东西:
var button = $(".button");
// fn to handle filtering and button-toggling
var toggleButton = function(settings) {
if (settings.url == "/specific/url")
button.button(button.button("option","disabled") ?
"enable" : "disable");
}
};
// bind handlers to the callbacks
button.ajaxSend(function(e,x,settings){
toggleButton(settings);
}).ajaxComplete(function(e,settings){
toggleButton(settings);
});
这也可以通过对传递给回调处理程序的设置对象执行相同类型的检查,通过前面提到的.ajaxSetup来完成。