5

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

例如,我提出我的 ajax 请求:

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

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

4

3 回答 3

6

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

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

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

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} );

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} );

EDIT

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) { // ...
于 2012-12-24T21:48:18.080 回答
2

使用直接取自文档的 ...访问url任何请求的示例:ajaxComplete

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()xhrsettings对象到你的浏览器控制台,你可以看到你可以访问的所有数据ajaxComplete

于 2012-12-24T22:32:14.697 回答
1

You can store the requests in an array and use the chained callbacks if that's what you mean:

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 );
  });
});
于 2012-12-24T21:48:13.623 回答