Home > Web Front-end > JS Tutorial > jQuery implements the method of monitoring all ajax requests on the page_jquery

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

WBOY
Release: 2016-05-16 15:26:19
Original
1355 people have browsed it

The example in this article describes how jQuery implements monitoring of all ajax requests on the page. Share it with everyone for your reference, the details are as follows:

Have you ever encountered such a problem: the page initiates two ajax requests, hoping that they will succeed before taking another action?

The easy solution to think of is to wait for one of them to end before initiating the other one. This process is completed using a callback function.

However, what should you do if one of the ajax request codes is not written by you and you cannot change it?

In other words, you just want to know when a certain URL request ends and don’t want to worry about other requests. How to do it?

<!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(){$('#test').append('all done!<br>');} //一行代码,就可以知道所有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: 'js/jquery-1.11.0.min.js', success: function(recv){$('#test').append('别人的ajax请求1,done<br>')}});
  </script>
  <script>
    $.get('css/main.css', null, function(recv){$('#test').append('别人的get请求,done<br>')});
  </script>
  <script>
    $.post('css/main.css', null, function(recv){$('#test').append('别人的post请求,done<br>')});
  </script>
</html>

Copy after login

Other related functions:

$.ajax:

error: called when an error occurs and can be used to report erroneous requests.
complete: Called regardless of success or failure

High version:

$.promise
$.when

I hope this article will be helpful to everyone in jQuery programming.

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