简体   繁体   中英

subscribe to jQuery.ajax() success event

I've a js which makes $.ajax call, on success of which, I need to do something. 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. I was wondering if there is a simple way to subscribe to the success event and handle it in my own js file

ajaxSuccess will be your friend for that : https://api.jquery.com/ajaxSuccess/

Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

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

But with this, you'll listen every ajax success event. 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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