我有 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 调用
最佳答案
您可以在jQuery.ajax()
中添加beforeSend
:
$.ajax({
type: "POST",
url: myUrl,
data: myData,
beforeSend: ajaxSpecificFunc
});
正如A.Wolff所指出的,这样,如果我们调用此函数,它将为每个调用绑定(bind)ajaxsend
。相反,您可以删除它并只执行特定的操作,例如:
function ajaxSpecificFunc(jqXHR, settings){
// you can work with the jqXhr and settings
}
关于javascript - 针对特定 ajax 调用在全局 $.ajax 事件上触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34286994/