简体   繁体   English

订阅jQuery.ajax()成功事件

[英]subscribe to jQuery.ajax() success event

I've a js which makes $.ajax call, on success of which, I need to do something. 我有一个js进行$.ajax调用,成功的话,我需要做点什么。 Typical implementation would be like: 典型的实现方式如下:

 $.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. 问题是,这个js函数是由另一个开发人员开发的,我依赖于那个ajax成功调用。 I was wondering if there is a simple way to subscribe to the success event and handle it in my own js file 我想知道是否有一种简单的方法来订阅成功事件并在我自己的js文件中处理它

ajaxSuccess will be your friend for that : https://api.jquery.com/ajaxSuccess/ ajaxSuccess将成为您的朋友: httpsajaxSuccess

Attach a function to be executed whenever an Ajax request completes successfully. 附加要在Ajax请求成功完成时执行的函数。 This is an Ajax Event. 这是一个Ajax事件。

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

But with this, you'll listen every ajax success event. 但有了这个,你会听到每个ajax成功事件。 So if you need to listen to only one request, you may need to do dhis : 因此,如果您只需要听一个请求,则可能需要执行以下操作:

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

You may use custom events: 您可以使用自定义事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM