如何从 XMLHttpRequest (AJAX) 调用 PHP 函数?

0 javascript php

我想知道是否可以使用 XMLHttpRequest (AJAX) 从外部文件调用 PHP 函数,如下所示。

索引.php

<script>

            var xhr = new XMLHttpRequest();
            xhr.open('POST','functions.php',true);
            
            xhr.onload = function(){
            //Here it is where I would like to call the function 
            console.log(this.responseText);
            }
            xhr.send(params);  
        }
</script>
Run Code Online (Sandbox Code Playgroud)

函数.php

<?php

    function hello(){
      echo "Hello from function php";
    }

?>
Run Code Online (Sandbox Code Playgroud)

在我的项目中,我使用的代码更复杂,但上面的示例更简单,这是我想使用 PHP 和 AJAX 调用我的函数的方式,我正在考虑添加<?php hello(); ?>内部 xhr.onload 函数,但它不起作用,有更好的想法如何做到这一点吗?我将不胜感激任何帮助..

Tha*_*der 5

您需要做的是让 PHP 函数在 PHP 文件被触发时运行。为此,请hello();在functions.php 的底部添加。要拥有多个函数,您可以拥有一个 php 文件文件夹,这些文件都执行一个函数。

如果你想要一个包含 JS 选择的多个函数的 PHP 文件,你可以这样做:

函数.php

<?php

$function = $_POST["function"];

if ($function == "hello") {
    hello();
}
else if ($function == "goodbye") {
    goodbye();
}

function hello() {
    echo "Hello from function php";
}

function goodbye() {
    echo "Goodbye from function php";
}

?>
Run Code Online (Sandbox Code Playgroud)

索引.php


<script>

var xhr = new XMLHttpRequest();
xhr.open('POST','functions.php',true);
xhr.onload = function() {
    console.log(this.responseText);
    // If you wanted to call the function in here, then just make another whole xhr var and send it in this function
}

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('function=hello');
</script>
Run Code Online (Sandbox Code Playgroud)

Eval 可以工作,但在客户端发送的数据上使用它是一个非常糟糕的主意(因为恶意请求可能会删除和读取服务器上的各种数据)