javascript - jQuery:$.ajaxSetup(beforeSend) 和 $(document).ajaxSend 之间有什么区别吗?

标签 javascript jquery ajax

使用 jQuery (v2.1.4),这两种方法有什么区别吗?

1) $.ajaxSetup(beforeSend)

$.ajaxSetup({
  beforeSend: function (jqXHR, settings) {
    // whatever you need to do before
    // any jQuery Ajax request is sent
  }
});

2) $(document).ajaxSend

$(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/

相关文章:

Javascript:获取按键的字符和位置

javascript - 如何使用 FlashCC 和 CreateJS 制作展开式广告?

javascript - 无法禁用动态 div 中的元素

jquery - 我可以在 CKEDITOR 中的元素上添加 onclick 事件吗?

javascript - 更改文档准备好时由 ajax 填充的选择的选定值?

javascript - 带有可滚动选择列表的 Bootstrap 下拉列表

javascript - 用户滚动后如何防止 2 个视频同时工作

javascript - Jquery 数据表 : where value is equal click closest checkbox

php - 关于 cookie 和 javascript 的安全问题

javascript - 如何使用 jQuery 从外部 URL 获取元标记