是否可以使用全局AJAX侦听器来获取AJAX调用的来源?

时间:2016-06-30 21:26:02

标签: javascript jquery ajax

请参阅this fiddle

如果我有以下代码:

HTML:

<div class="button-wrapper">
  <button id='firstButton'>
    first button
  </button>
  <button id='secondButton'>
    second button
  </button>
</div>

JS:

$("button").click(function(event) {
    var targetId = event.target.id;
    $.ajax({
    type: "GET",
    url: "https://fiddle.jshell.net",
    success: function(data) {
        alert('target id is: ' + targetId);
    }
  });
});

// Is it possible for this to work the same as the above somehow?
$(document).ajaxSuccess(function(event, xhr, ajaxOptions, data) {
  var targetId = event.target.id; // Event.target is `document` so does not work
  alert('target id is: ' + targetId); // I want this to be the same alert as above.
});

是否可以将触发AJAX调用的按钮的id传递给全局侦听器($(document).ajaxSuccess)?

2 个答案:

答案 0 :(得分:3)

当然,将它与ajax选项一起传递,然后从ajax选项中提取它。

http://jsfiddle.net/tsmknfr2/6

$("button").click(function(e) {
  var targetId = event.target.id;
  $.ajax({
    type: "GET",
    url: "https://fiddle.jshell.net",
    success: function(data) {
        alert('target id is: ' + targetId);
    },
    foop: targetId
  });
});

// Is it possible for this to work the same as the above somehow?
$(document).ajaxSuccess(function(event, xhr, ajaxOptions, data) {
  var targetId = ajaxOptions.foop; 
  alert('target id is: ' + targetId); 
});

答案 1 :(得分:1)

您可以预先定义一个选择加入绑定的函数。每次要在回调之前首先运行警报时,都可以使用此功能。在$.ajax选项中包含您计划在函数中访问的所有字段。

这比拥有全局$.ajax捕获器或修改$.ajax函数更好,因为它不会污染页面中没有关联{{1}的所有ajax请求}}

id

JSFiddle