Home > Web Front-end > JS Tutorial > body text

jQuery implements the method of monitoring all ajax requests on the page

不言
Release: 2018-07-02 14:24:34
Original
2024 people have browsed it

这篇文章主要介绍了jQuery实现监控页面所有ajax请求的方法,涉及jQuery中ajax请求的判定技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了jQuery实现监控页面所有ajax请求的方法。分享给大家供大家参考,具体如下:

你是不是有遇到这样的问题:页面发起两个ajax请求,希望它们都成功以后,再做一个动作?

很容易想到的解决方案是,等其中一个结束以后,再发起另外一个,这个过程用回调函数来完成。

但是,如果其中一个ajax请求的代码不是你写,你改不了,怎么办?

又或者说,你只想知道某个url请求什么时候结束,不想管其他的请求,怎么弄?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <p id="test"></p>
  </body>
  <script src="js/jquery-1.11.0.min.js"></script>
  <!--首先在页面引入jquery的后面,紧接着以下代码:-->
  <script>
    //前提:所有ajax请求都是用jquery的$.ajax发起的,而非原生的XHR;
    var ajaxBack = $.ajax;
    var ajaxCount = 0;
    var allAjaxDone = function(){$(&#39;#test&#39;).append(&#39;all done!<br>&#39;);} //一行代码,就可以知道所有ajax请求什么时候结束
    //由于get/post/getJSON等,最后还是调用到ajax,因此只要改ajax函数即可
    $.ajax = function(setting){
      ajaxCount++;
      var cb = setting.complete;
      setting.complete = function(){
        if($.isFunction(cb)){cb.apply(setting.context, arguments);}
        ajaxCount--;
        if(ajaxCount==0 && $.isFunction(allAjaxDone)){
          allAjaxDone();
        }
      }
      ajaxBack(setting);
    }
  </script>
  <!--以下是别人的script-->
  <script>
    $.ajax({url: &#39;js/jquery-1.11.0.min.js&#39;, success: function(recv){$(&#39;#test&#39;).append(&#39;别人的ajax请求1,done<br>&#39;)}});
  </script>
  <script>
    $.get(&#39;css/main.css&#39;, null, function(recv){$(&#39;#test&#39;).append(&#39;别人的get请求,done<br>&#39;)});
  </script>
  <script>
    $.post(&#39;css/main.css&#39;, null, function(recv){$(&#39;#test&#39;).append(&#39;别人的post请求,done<br>&#39;)});
  </script>
</html>
Copy after login

其他的相关函数:

$.ajax 中:

error:当出错时调用,可以用来上报错误的请求。
complete:无论成功还是失败都会调用

高版本中:

$.promise
$.when

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

基于jQuery 实现bootstrapValidator下的全局验证

jQuery实现ajax调用WCF服务的方法介绍

The above is the detailed content of jQuery implements the method of monitoring all ajax requests on the page. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!