针对特定ajax调用的全局$.ajax事件的触发器函数

Trigger function on a global $.ajax event for a specific ajax call

本文关键字:ajax 事件 函数 触发器 全局 调用      更新时间:2023-09-26

我有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所指出的,通过这种方式,如果我们调用此函数,它将为每个调用绑定ajaxsend。相反,你可以删除它,只做特定的事情,比如:

function ajaxSpecificFunc(jqXHR, settings){
   // you can work with the jqXhr and settings
}

如果你不能将处理程序直接绑定到ajax调用,并且只想使用全局处理程序,那么你可以检查设置对象,看看ajax调用是否是你的目标,如果是,那么调用你的东西

$(document).ajaxSend(function(event, jqXHR, settings) {
  console.log('send', settings);
  if (settings.url == 'myurl') {
    //then do your stuff
  }
})

注意:但这可能有些过头了,您应该尝试针对您的ajax调用

来做这件事