如何在所有ajax调用之后调用javascript函数?

我想在所有ajax调用之后调用一些javascript函数。

当然,我知道如何在每个单独的ajax调用中调用函数:

function xyz()
{

if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("links").innerHTML=xmlhttp.responseText;

     *****javacsript would go here*****
   }

 xmlhttp.open("GET","xhr_php/site_links.php",true);
 xmlhttp.send();
 }
 }

同样,我知道如何在每个ajax调用之后或内部调用它,但是我想知道是否有一个函数会在所有ajax调用之后调用这些函数。这样的话,我就不必在每个Ajax调用中编写javascript。

我认为这与endrequesthandler有关,但不确定如何用php / javascript编写。 我在网上发现了一些东西,但它们都与asp.net有关,而我使用的是php。

此外我也想找一个在ajax调用开始时或ajax调用之前调用函数的方法。通过这种方式,我可以在ajax调用期间启动和停止,而不必在每次调用中都编写该函数。

谢谢帮助!

You can have it take a callback function:

function xyz(callback) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(this);
        }

    }
    xmlhttp.open("GET", "xhr_php/site_links.php", true);
    xmlhttp.send();
}

Then:

xyz( function( xhr ) {

    alert( xhr.responseText );

});

You can centralize Ajax calls using single function or object, and before issue any ajax call you can insert any function to a global stack (array).

global_callbacks.push(function(){alert('');});

Your central ajax caller can call all the functions on the stack.

var global_callbacks = [];

function xyz() {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            for(var i=0; i < global_callbacks.length; ++i)
                 global_callbacks[i]();
        }

    }
    xmlhttp.open("GET", "xhr_php/site_links.php", true);
    xmlhttp.send();
}