使用 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
- “Opened”)。
这意味着如果调用 $.ajax()
时将 global
选项设置为 false
,则 ajaxSend()
方法不会触发。
在 $.ajaxSetup()
上,您实际上是在为每个 jQuery Ajax 调用的设置创建默认值,并且通过 beforeSend
选项定义的回调将始终是已调用(XMLHttpRequest.readyState
值为 0
- “Unsent”)。
关于javascript - jQuery:$.ajaxSetup(beforeSend) 和 $(document).ajaxSend 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32628823/