我有几个 HTML 元素,单击时会启动 ajax。如何检查在 ajaxComplete
事件中单击了哪个元素?
我尝试了 event.target
但它返回了整个文档。
$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url.indexOf("somelink/hello") > -1) {
console.log("return here element that initiated ajax")
}
});
注意:棘手的部分 - 我无权访问点击时发送的 ajax 请求。我无法配置发出请求的代码。我只能检查ajax何时完成。
我首先需要运行 ajaxComplete
事件,然后检查哪个元素启动了 ajax,因为我需要向该元素添加一些 html。因此,我尝试 checkin ajaxComplete
事件。
最佳答案
$.ajaxComplete()
处理程序不是特定于对象的处理程序;您将其附加到文档中,以便在任何 AJAX 请求完成时收到通知。来自 jQuery 文档:
If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request.
因此,由于 settings
是一个普通对象,因此您可以使用一个属性来扩展它,然后将该属性传递给处理程序,如下面的 requestingObjectId
所示。 <强> DEMO
var onComplete = function(event, jqXHR, ajaxOptions) {
alert("Requested with " + ajaxOptions.requestingObjectId);
};
var makeRequest = function() {
var id = $(this).attr('id');
$.ajax({
url: '/path/to/server',
data: { foo: 1 },
requestingObjectId: id
});
};
$('button').click(makeRequest);
$(document).ajaxComplete(onComplete);
关于javascript - Jquery:什么 HTML 元素启动 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28367960/