Home>

Have you encountered such a problem:the page initiates two ajax requests, hope that after both of them succeedOne more action?

The easy solution came to mind is,When one of them ends,Launch another one,This process is done using callback functions.

However, if the code for one of the ajax requests was not written by you,You can't changeHow to do?

Or,You just want to know when a certain url request ends,Don't want to care about other requests,how to do?

<! Doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <p></p>
  </body>
  <script src="js/jquery-1.11.0.min.js"></script>
  <!-First introduce jquery on the page, followed by the following code:->
  <script>
    //Premise:All ajax requests are initiated using jquery's $.ajax, not native xhr;
    var ajaxback=$.ajax;
    var ajaxcount=0;
    var allajaxdone=function () {$("#test"). append ("all done!<br>");} //One line of code,You can know when all ajax requests end
    //Because of get/post/getjson, etc., ajax is still called at the end, so just change the ajax function.
    $.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>
  <!-The following is someone else's script->
  <script>
    $.ajax ({url:"js/jquery-1.11.0.min.js", success:function (recv) {$("#test"). append ("Others' ajax request 1, done<br>" ))});
  </script>
  <script>
    $.get ("css/main.css", null, function (recv) {$("#test"). append ("get request from someone else, done<br>")});
  </script>
  <script>
    $.post ("css/main.css", null, function (recv) {$("#test"). append ("Other's post request, done<br>")});
  </script>
</html>

Other related functions:

$.ajax:

error:called when an error occurs,Can be used to report bad requests.

complete:called on success or failure

In high version:

$.promise

$.when

  • Previous C ++ implementation to find the greatest common divisor and the least common multiple
  • Next Examples of related PHP scripts for debugging timed tasks in WordPress