使用jQuery (v2.1.4),这两种方法之间有什么区别吗?
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
}
});
2) $(文档).ajaxSend
$(document).ajaxSend(function (event, jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
});
有什么理由选一个比另一个好吗?
谢谢!
发布于 2015-09-17 11:21:38
来自jQuery $.ajaxSetup()
文档:
所有使用任何函数的后续Ajax调用都将使用新设置,除非被单独的调用覆盖,直到下一次调用$.ajaxSetup()为止。
$.ajaxSetup()
所做的事情如下:
ajaxExtend(jQuery.ajaxSettings, target);
来自$.ajaxSend()
文档:
每当要发送Ajax请求时,jQuery都会触发ajaxSend事件。此时将执行已在.ajaxSend()方法中注册的任何和所有处理程序。
以及用于jQuery的$.ajaxSend()
源代码:
function (fn) {
return this.on(type, fn);
}
因此,基本上,$(document).ajaxSend()
向所有文档中添加了一个事件侦听器,在该文档中,只要要发送jQuery Ajax调用,就可以使任何处理程序执行它(处理程序拦截它,但是XMLHttpRequest.readyState
值已经是1
--“已打开”)。
这意味着,如果调用$.ajax()
时将global
选项设置为false
,则ajaxSend()
方法将不会触发。
在$.ajaxSetup()
上,您实际上是为每个jQuery Ajax调用的设置创建默认值,并且通过beforeSend
选项定义的回调将始终被调用(XMLHttpRequest.readyState
值是0
-- "Unsent")。
发布于 2015-09-17 11:26:53
两者功能非常相似,但它总是取决于需要
$.ajax()
时全局选项设置为false,则ajaxSend()
方法将不会触发。beforeSend
选项。从优先级的角度来看,您可以以这种方式使用ajaxSend
中的所有设置选项,对于自定义或特定的ajax请求,可以在$.ajax()
中使用beforeSend
覆盖它。
<body>
<div><h2>Let AJAX change this text</h2></div>
<button id="btn1">Change Content</button>
<button id="btn2">Change Content Override</button>
</body>
JS
$(document).ajaxSend(function(e, xhr, opt){
$("div").append("<p>Requesting " + opt.url + "</p>");
});
$("#btn1").click(function(){
$("div").load("yourpage.html");
});
$("#btn2").click(function(){
$.ajax({
global: false,
beforeSend:function(){$("div").append("<p>Overriding</p>");}
});
$("div").load("yourpage.html");
});
LIVE http://jsfiddle.net/mailmerohit5/w8t44247/
发布于 2015-09-17 11:44:16
来自JQuery的文档:
有两种类型的事件: 本地事件--这些回调可以在Ajax请求对象中订阅,如下所示:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
全球事件 这些事件在文档上触发,调用可能正在侦听的任何处理程序。您可以这样收听这些事件:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
可以通过传入全局选项来禁用特定Ajax请求的全局事件,如下所示:
$.ajax({
url: "test.html",
global: false,
// ...
});
https://stackoverflow.com/questions/32628823
复制相似问题