【发布时间】:2012-12-24 21:42:51
【问题描述】:
有没有办法监控页面上使用 JQuery 发出的所有 ajax 请求,并根据每个请求的结果调用回调函数?
例如,我提出我的 ajax 请求:
$.get('foo', {foo: bar} );
$.get('bar', {bar: foo} );
然后,每次完成任何这些 ajax 请求时,我都会调用一个函数,其中包含引用的 url,以及请求的结果?
【问题讨论】:
标签: javascript jquery ajax
有没有办法监控页面上使用 JQuery 发出的所有 ajax 请求,并根据每个请求的结果调用回调函数?
例如,我提出我的 ajax 请求:
$.get('foo', {foo: bar} );
$.get('bar', {bar: foo} );
然后,每次完成任何这些 ajax 请求时,我都会调用一个函数,其中包含引用的 url,以及请求的结果?
【问题讨论】:
标签: javascript jquery ajax
查看 jQuery 的“ajaxComplete”;它应该正是您正在寻找的:
http://api.jquery.com/ajaxComplete/
使用它,您可以注册一个处理程序,该处理程序将在每次 ajax 调用时被调用。
$.ajaxComplete(function() {
alert('it worked');
});
$.get('foo', {foo: bar} ); // "it worked" would get alerted when this completes
要查看返回的响应,只需使用提供的 XHR 对象,如下所示:
$.ajaxComplete(function(e, xhr) {
alert('it worked, and the response was:' + xhr.responseHTML);
});
$.get('foo', {foo: bar} );
要检查 URL,您可以使用提供的第三个“设置”参数:
$.ajaxComplete(function(e, xhr, settings) {
alert('it worked, and the response was:' + xhr.responseHTML);
alert('and the original URL was:' + settings.url);
});
$.get('foo', {foo: bar} );
编辑
正如 Yusuf K. 在 cmets 中很有帮助地指出的那样,如果您使用的是 jQuery 3 等新版本之一,事情就会发生变化。 ajaxComplete 不再是静态方法,而是您在 document 上调用的实例方法:
$(document).ajaxComplete(function(e, xhr, settings) { // ...
【讨论】:
使用ajaxComplete 访问url 的任何请求的示例...直接取自文档:
http://api.jquery.com/ajaxComplete/
$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler. The result is ' +
xhr.responseHTML);
}
});
如果您 console.log() xhr 和 settings 对象到您的浏览器控制台,您可以在 ajaxComplete 中看到您可以访问的所有数据
【讨论】:
如果您的意思是这样,您可以将请求存储在数组中并使用链式回调:
function callback( data ) {
// do something with the request
}
var requests = [];
requests.push( $.get('foo', { foo: bar }) ); // add to array and run request
requests.push( $.get('bar', { bar: foo }) );
requests.forEach(function( request ) {
request.done(function( data ) {
callback( data );
});
});
【讨论】: