如何在javascript中调用php函数

如何在javascript中调用php函数,javascript,php,Javascript,Php,我有一个php函数。我想在javascript函数中调用它。怎么做? 我的php函数是 <?php function image_save(){ $img = $_POST['image']; $folderPath = "C:/xampp/htdocs/"; $image_parts = explode(";base64,", $img); $image_type_aux = explode("image/",

我有一个php函数。我想在javascript函数中调用它。怎么做? 我的php函数是

<?php
    function image_save(){
        $img = $_POST['image'];

        $folderPath = "C:/xampp/htdocs/";

        $image_parts = explode(";base64,", $img);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];

        $image_base64 = base64_decode($image_parts[1]);
        $fileName = '1'. '.jpeg';

        $file = $folderPath . $fileName;
        file_put_contents($file, $image_base64);

        print_r($fileName);
        $command = escapeshellcmd("python C:/xampp/htdocs/generate_graph.py");
        $output = shell_exec($command);
    }

?>


您可以从运行在Broswer上的js调用API,而不是直接调用PHP函数。

如果您想从Javascript调用PHP函数,需要向运行此函数的服务器发送XMLHttpRequest。Javascript正在浏览器中运行,在客户端计算机上运行。PHP正在你的服务器上运行,在某个数据中心的某处。因此,不可能直接从Javascript调用PHP函数

XmlHttpRequest将http请求(POST | GET |…)发送到服务器并等待其输出。在您的例子中,您将调用服务器上的一个php文件并等待它的响应

还有许多库可以以更简单的方式执行XMLHttpRequest

你也可以提交一份表格,这样可能会更容易

<form action="/yourPHPFunctionUrl">
<!-- some inputs -->
<button type="submit">Send me ! </button>
</form>

派我来!

本质上,您不能在javascript函数中调用php函数。如果使用ajax发出请求并使用回调来处理php函数的响应,则可以调用php函数,也可以通过提交表单或使用ajax
<form action="/yourPHPFunctionUrl">
<!-- some inputs -->
<button type="submit">Send me ! </button>
</form>