php - Javascript 端 RequestHandler

标签 php javascript ajax function

我想在所有 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 调用期间启动和停止函数,而不必在每次调用中都写这个。

感谢您的帮助。

最佳答案

你可以让它接受一个回调函数:

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

然后:

xyz( function( xhr ) {

    alert( xhr.responseText );

});

关于php - Javascript 端 RequestHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609686/

相关文章:

PHP (cli) 从/dev/tty 读取时吞下一个字节

javascript - JSDoc 中对象中任意键值的文档结构

javascript - json 中数组和对象的混淆

c# - 为什么这个 AJAX 调用返回整个页面内容?

php - 在数组中的表单请求 laravel 中附加数据

javascript - React js渲染从服务器返回的html字符串

javascript - 使用 Backbone.history 时如何处理修改后的模型

javascript - JQuery Mobile 在导航页面后丢失所有样式

javascript - 我需要使用 AJAX Post 声明结果类型吗?

PHP/MySQL Web 应用程序使用枚举数据库字段进行国际化