使用jQuery(v2.1.4),这两种方法有什么区别吗?
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
}
});
$(document).ajaxSend(function (event, jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
});
有什么理由比较喜欢一个吗?
谢谢!
最佳答案 从jQuery
$.ajaxSetup()
文档:
All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().
$.ajaxSetup()执行如下操作:
ajaxExtend(jQuery.ajaxSettings, target);
从$.ajaxSend()
文件:
Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.
$.ajaxSend()的jQuery源代码:
function (fn) {
return this.on(type, fn);
}
所以,基本上$(document).ajaxSend()为所有文档添加一个事件监听器,你可以在任何时候发送jQuery Ajax调用时执行任何处理程序(处理程序拦截它,但XMLHttpRequest.readyState
值已经是1) – “打开”).
这意味着如果在全局选项设置为false的情况下调用$.ajax(),则不会触发ajaxSend()方法.
在$.ajaxSetup()上,您实际上是为每个jQuery Ajax调用的设置创建默认值,并且将始终调用通过beforeSend选项定义的回调(XMLHttpRequest.readyState值为0 – “未发送”).