订阅jQuery.ajax()成功事件

4

我有一个JS脚本,其中调用了$.ajax方法,在成功后需要执行某些操作。典型的实现方式如下:

$.ajax({
    url: "/Sales/Quotations/LinkQuotabtleItemToSites",
    type: "POST",
    success: function (data) {
        // do something
    }
});

The issue is, this js function is developed by another developer and I've dependency on that ajax success call. I was wondering if there is a simple way to subscribe to the success event and handle it in my own js file


你只想在整个项目中调用这一个Ajax吗?请确认一下。 - Ram Singh
目前是这样的,但我不知道将来我的逻辑是否会依赖于其他Ajax调用(业务规则变更..你懂的)。 - Mahesh Kava
1
请尝试按照上述链接。 - Ram Singh
2
“订阅”成功事件听起来像是个可怕的想法。我确定你真的需要使用版本控制。这就是全世界程序员的工作方式。请阅读以下文章:https://dev59.com/RHM_5IYBdhLWcg3wXx5N 和https://dev59.com/FXVD5IYBdhLWcg3wXacd。"因此我们可以独立工作,而不会覆盖对方的更改"。 - Yeldar Kurmangaliyev
谢谢Ram提供的链接,是否可以订阅特定的调用,然后有一个全局回调处理程序? - Mahesh Kava
2个回答

6

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 !');
  }
});

0

您可以使用自定义事件:

$('.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);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接