我有3-4个ajax调用,它们会在某个时候被调用。对于其中一个调用,我想在ajaxSend事件上触发一个函数,该事件是全局的。这个特定的ajax调用不一定是序列中的第一个或最后一个。似乎如果我将ajaxSend事件附加到$(document),我的函数将在每隔一次ajaxSend事件发生时触发。下面是我的代码:
//ajax call one
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call two <- let's say I'd like to fire ajaxSpecificFunc() here
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call three
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
function ajaxSpecificFunc(){
$(document).on("ajaxSend", function() {
//Some code that should only happen on ajaxSend but for only one ajax call
});
}编辑:我知道ajax的global:false属性,但不希望使用它,因为这意味着我将来必须修改每个新的ajax调用,才能让ajaxSpecificFunc()继续为一个特定的ajax调用触发
发布于 2015-12-15 18:42:59
您可以在jQuery.ajax()中添加beforeSend:
$.ajax({
type: "POST",
url: myUrl,
data: myData,
beforeSend: ajaxSpecificFunc
});正如A.Wolff所指出的,通过这种方式,如果我们调用此函数,它将为每次调用绑定ajaxsend。相反,您可以删除它,只执行特定的操作,如:
function ajaxSpecificFunc(jqXHR, settings){
// you can work with the jqXhr and settings
}发布于 2015-12-15 18:50:22
如果您不能将处理程序直接绑定到ajax调用,并且只想使用全局处理程序,那么您可以检查设置对象,以查看ajax调用是否是您的目标,如果是,则调用您的程序
$(document).ajaxSend(function(event, jqXHR, settings) {
console.log('send', settings);
if (settings.url == 'myurl') {
//then do your stuff
}
})注意:但是这可能是一种过度的杀伤力,您应该尝试针对您的ajax调用执行此操作
https://stackoverflow.com/questions/34286994
复制相似问题