【问题标题】:Monitoring all AJAX requests made by JQuery?监控 JQuery 发出的所有 AJAX 请求?
【发布时间】:2012-12-24 21:42:51
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    查看 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(function().. 不起作用,但如给定链接中所述 $( document ).ajaxComplete(function().. 与 JQUERY 3.1.1 一起使用
    • 感谢您提及,我已将其添加到我的答案中。
    • 不客气,感谢您快速编辑答案。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      如果您的意思是这样,您可以将请求存储在数组中并使用链式回调:

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

      【讨论】:

      • 您也可以使用 jQuery 的延迟类(从 ajax 调用返回的东西的类)来减少冗长(尽管出于可读性原因我不一定推荐它):@ 987654322@
      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2012-11-13
      • 1970-01-01
      相关资源
      最近更新 更多