监控JQuery发出的所有AJAX请求?

Cli*_*ote 4 javascript ajax jquery

有没有办法监视在页面上使用JQuery进行的所有ajax请求,并使用每个请求的结果调用回调函数?

例如,我发出了我的ajax请求:

$.get('foo', {foo: bar} );
$.get('bar', {bar: foo} );
Run Code Online (Sandbox Code Playgroud)

然后,每次完成任何ajax请求时,我都会调用一个函数,其中包含引用的url和请求的结果?

mac*_*ost 6

查看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
Run Code Online (Sandbox Code Playgroud)

要查看返回的响应,只需使用提供的XHR对象,如下所示:

$.ajaxComplete(function(e, xhr) {
    alert('it worked, and the response was:' + xhr.responseHTML);
});

$.get('foo', {foo: bar} );
Run Code Online (Sandbox Code Playgroud)

要检查URL,您可以使用提供的第三个"设置"arg:

$.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} );
Run Code Online (Sandbox Code Playgroud)

编辑

正如Yusuf K.在评论中有用地指出的那样,如果你正在使用jQuery 3等jQuery的新版本之一,那么事情已经发生了变化.ajaxComplete不再是静态方法,而是您调用的实例方法document:

$(document).ajaxComplete(function(e, xhr, settings) { // ...
Run Code Online (Sandbox Code Playgroud)