订阅jQuery.ajax()成功事件

subscribe to jQuery.ajax() success event

本文关键字:成功 事件 jQuery ajax 订阅      更新时间:2023-09-26

我有一个使$.ajax调用的js,在成功的情况下,我需要做一些事情。典型的实现是这样的:

$.ajax({
    url: "/Sales/Quotations/LinkQuotabtleItemToSites",
    type: "POST",
    success: function (data) {
        // do something
    }
});
问题是,这个js函数是由另一个开发人员开发的,我依赖于ajax成功调用。我想知道是否有一种简单的方法来订阅成功事件并在我自己的js文件

中处理它

ajaxSuccess将是您的朋友:https://api.jquery.com/ajaxSuccess/

附加一个在Ajax请求成功完成时执行的函数。这是一个Ajax事件

$(document).ajaxSuccess(function(event, xhr, settings) {
  console.log('hello !');
});

但是有了这个,您将侦听每个ajax成功事件。因此,如果您只需要监听一个请求,您可能需要这样做:

$(document).ajaxSuccess(function(event, xhr, settings) {
  if (settings.url == '/foo/bar/somefile') {
      console.log('hello !');
  }
});

您可以使用自定义事件:

$('.my-link').click(function() {
  $.ajax({
    url: "/Sales/Quotations/LinkQuotabtleItemToSites",
    type: "POST",
    success: function(response) {
      $(document).trigger('mynamespace:mytrigger', [response]);
    }
  });
});
// Developer 1 listens:
$(document).on('mynamespace:mytrigger', function (event, response) {
  console.log('Listener 1 and response is:', response);
});

// Developer 2 listens in some other place:
$(document).on('mynamespace:mytrigger', function (event, response) {
  console.log('Listener 2 and response is:', response);
});