How can I call PHP functions by JavaScript?

后端 未结 11 1211
情话喂你
情话喂你 2020-11-22 12:08

I am trying to call a PHP function from an external PHP file into a JavaScript script. My code is different and large, so I am writing a sample code here.

This is m

11条回答
  •  死守一世寂寞
    2020-11-22 12:39

    This work perfectly for me:

    To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.

    I found a way:

    This for JavaScript:

    function callPHP(expression, objs, afterHandler) {
            expression = expression.trim();
            var si = expression.indexOf("(");
            if (si == -1)
                expression += "()";
            else if (Object.keys(objs).length > 0) {
                var sfrom = expression.substring(si + 1);
                var se = sfrom.indexOf(")");
                var result = sfrom.substring(0, se).trim();
                if (result.length > 0) {
                    var params = result.split(",");
                    var theend = expression.substring(expression.length - sfrom.length + se);
                    expression = expression.substring(0, si + 1);
                    for (var i = 0; i < params.length; i++) {
                        var param = params[i].trim();
                        if (param in objs) {
                            var value = objs[param];
                            if (typeof value == "string")
                                value = "'" + value + "'";
                            if (typeof value != "undefined")
                                expression += value + ",";
                        }
                    }
                    expression = expression.substring(0, expression.length - 1) + theend;
                }
            }
            var doc = document.location;
            var phpFile = "URL of your PHP file";
            var php =
                "$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
                "$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
                "set_include_path($folder);include $fileName;" + expression + ";";
            var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
            $.ajax({
                type: 'GET',
                url: url,
                complete: function(resp){
                    var response = resp.responseText;
                    afterHandler(response);
                }
            });
        }
    


    This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:

    
    


    So, your PHP code remain equals except return values, which will be echoed:

    
    


    I suggest you to remember that jQuery is required:
    Download it from Google CDN:

    
    

    or from Microsoft CDN: "I prefer Google! :)"

    
    

    Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!

    The choice is to you!


    Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

    //Names of parameters are custom, they haven't to be equals of these of the PHP file.
    //These fake names are required to assign value to the parameters in PHP
    //using an hash table.
    callPHP("add(num1, num2)", {
                'num1' : 1,
                'num2' : 2
            },
                function(output) {
                    alert(output); //This to display the output of the PHP file.
            });
    

提交回复
热议问题