簡體   English   中英

訂閱jQuery.ajax()成功事件

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

我有一個js進行$.ajax調用,成功的話,我需要做點什么。 典型的實現方式如下:

 $.ajax({ url: "/Sales/Quotations/LinkQuotabtleItemToSites", type: "POST", success: function (data) { // do something } }); 
問題是,這個js函數是由另一個開發人員開發的,我依賴於那個ajax成功調用。 我想知道是否有一種簡單的方法來訂閱成功事件並在我自己的js文件中處理它

ajaxSuccess將成為您的朋友: httpsajaxSuccess

附加要在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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM