【问题标题】:How to call a php function in javascript [duplicate]如何在javascript中调用php函数[重复]
【发布时间】:2019-11-21 21:23:21
【问题描述】:

我在 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);
    }

?>

【问题讨论】:

  • 本质上你不能在 javascript 函数中调用 php 函数。如果您使用ajax发出请求并使用回调来处理您的PHP函数的响应,则可以调用php函数
  • 要么提交表单,要么使用 ajax

标签: javascript php


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    XmlHttpRequest 向服务器发送一个 http 请求 ( POST | GET | ... ) 并等待它的输出。在您的情况下,您将调用服务器上的 php 文件并等待它的响应。

    From Javascript.info

    // 1. Create a new XMLHttpRequest object
    let xhr = new XMLHttpRequest();
    
    // 2. Configure it: GET-request for the URL
    xhr.open('GET', '/yourPhPfileLocationUrl/');
    
    // 3. Send the request over the network
    xhr.send();
    
    // 4. This will be called after the response is received
    xhr.onload = function() {
      if (xhr.status != 200) { // analyze HTTP status of the response
        alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
      } else { // show the result
        alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
      }
    };
    
    xhr.onprogress = function(event) {
      if (event.lengthComputable) {
        alert(`Received ${event.loaded} of ${event.total} bytes`);
      } else {
        alert(`Received ${event.loaded} bytes`); // no Content-Length
      }
    
    };
    
    xhr.onerror = function() {
      alert("Request failed");
    };
    

    还有许多库可以做更简单的 XMLHttpRequest。

    您也可以提交表单,这可能更容易。

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

    【讨论】:

      猜你喜欢
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2012-11-29
      • 2015-06-13
      • 2015-06-01
      • 2013-06-03
      • 2012-02-10
      相关资源
      最近更新 更多