监视JQuery发出的所有AJAX请求? [英] Monitoring all AJAX requests made by JQuery?

查看:98
本文介绍了监视JQuery发出的所有AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以监视在页面上使用JQuery发出的所有ajax请求,并使用每个请求的结果调用回调函数?

Is there a way to monitor all ajax requests that have been made using JQuery on a page, and to have a callback function be called with the result of each request?

例如,我提出了ajax请求:

E.g I make my ajax requests:

$.get('foo', {foo: bar} );
$.get('bar', {bar: foo} );

然后,每当这些ajax请求中的任何一个完成,带有被引用的url以及请求的结果时,我都有一个函数调用?

And then I have a function called each time any of those ajax requests is completed, with the url that was referenced, and the result of the request?

推荐答案

查看jQuery的"ajaxComplete";它应该正是您要寻找的:

Check out jQuery's "ajaxComplete"; it should be exactly what you're looking for:

http://api.jquery.com/ajaxComplete/

使用它,您可以注册一个处理程序,该处理程序将在每次ajax调用时被调用.

Using it, you can register a handler and that handler will get invoked on every ajax call.

$.ajaxComplete(function() {
    alert('it worked');
});

$.get('foo', {foo: bar} ); // "it worked" would get alerted when this completes

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

To see the response that came back, just use the XHR object that gets provided, like so:

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

$.get('foo', {foo: bar} );

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

And to check the URL you can use a third "settings" arg that gets provided:

$.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.在评论中有帮助地指出的那样,如果您使用的是jQuery 3之类的jQuery新版本,则情况已经发生了变化. ajaxComplete 不再是静态方法,而是您在 document 上调用的实例方法:

As Yusuf K. helpfully pointed out in the comments, if you're using one of the new versions of jQuery such as jQuery 3, things have moved around. ajaxComplete is no longer a static method, but is instead an instance method that you call on document:

$(document).ajaxComplete(function(e, xhr, settings) { // ...

这篇关于监视JQuery发出的所有AJAX请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆