简体   繁体   English

使用php和js从客户端执行服务器和客户端功能

[英]Executing Server and Client functions from client side with php and js

After the client presses a button - a server side function must be executed and according the result different client side functions be executed.. 客户端按下按钮后-必须执行服务器端功能,并根据结果执行不同的客户端功能。

To achive this I used AJAX and wrote this function : 为此,我使用了AJAX并编写了以下函数:

function invoke_php(file_name, parameters){     
   parameters = typeof parameters !== 'undefined' ? parameters : '';
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {             
           switch (xmlhttp.responseText) {
             case "func1":
                func1();
             break;
             case "func2":
                func2();
             break;
             default:
                default_func();
           } 
       }
   };
   xmlhttp.open("POST", file_name+"?"+parameters, true);
   xmlhttp.send();
}

Server side functionality is performed in separate php file, which returns the name of the function to run. 服务器端功能在单独的php文件中执行,该文件返回要运行的函数的名称。 the invoke_php function uses switch on the respone text and execute the suitable client-side function... invoke_php函数使用respone文本上的开关并执行适当的客户端函数...

It feels like there is a better way to do this.... Any improvement suggestion will be appreciated..:) 感觉有更好的方法来执行此操作。任何改进建议将不胜感激.. :)

I would recommend you to: 我建议您:

  1. remove the switch case (which is usually not efficient and tend to become very verbose) 删除开关盒(通常效率不高,并且变得非常冗长)
  2. pass the full URL to the function 将完整的URL传递给函数
  3. pass the list of callbacks to the function, in that way you won't rely on global definition of callbacks 将回调列表传递给函数,那样您就不必依赖回调的全局定义

Here is what the code could look like: 代码如下所示:

function invoke_php(url, callbacks){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && callbacks) {
            var fn = callbacks[xmlhttp.responseText] || callbacks._default || function () {};
            fn();
        }
    };
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

invoke_php(
    'test.php?myparams=true',
    {
        _default: function () {},
        func1: function () {
            console.log('func1');
        },
        func2: function () {
            console.log('func2');
        },
    }
);

Let me know if this helps. 让我知道是否有帮助。

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM