传递参数给服务器端的PHP文件中的特定函数(从JS中),然后将结果返回给调用该函数的JS函数
P粉593649715
P粉593649715 2024-01-16 22:27:27
0
1
430

基本上我正在做的是创建一个图形计算器(使用 BokehJS),该计算器当前通过 html 获取一些输入,然后 javascript 读取数据并进行计算,然后输出结果图形。

问题是我们不希望用户能够看到所有的计算代码。 如果他们能看到 getter 和 setter 方法就很好了。

我需要它做的是:

  1. 获取 HTML 页面上的用户输入
  2. 使用 JavaScript 读取输入(客户端)
  3. 将读取的输入数据传递给 PHP(在 WordPress 服务器上)进行计算
  4. PHP 将结果数据发送回 JS
  5. JS(客户端)处理要做什么以及如何显示数据

我们正在使用 WordPress 服务器,目前我只是在本地计算机上进行测试,因此允许测试和部署的方式会很棒。

目前这是我所拥有的:

myjavascript.js

function test_test(){

    const staticPNVals = getStaticPN(); //send this to php file as parameter to function
    const ret_array = [];
    
    //The below needs to be changed, idk how to do it
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        const myObj = JSON.parse(this.responseText);
        ret_array = myObj;
    }
    xmlhttp.open("GET", "test.php");
    xmlhttp.send();

    console.log("ret_array is " + ret_array);
}

测试.php

<?php
function doStuff($myarr) {
    $myarr2 = array();
    for ($x = 0; $x <= 10; $x++) {
        array_push($myarr2, $myarr[$x]);
      }
    return $myarr2;
}

function doOtherStuff(){
    echo "Hello World";
}
?>

我希望拥有它,这样我就可以在一个文件中拥有多个函数,我看到的大多数解决方案每个文件中只有 1 个函数。

mypage.html

<!-- Just a simple button to call the main Javascript function-->
<input type="button" value="Test function" onclick="test_test()">

所以基本上,总体问题是我如何更改 javascript 请求,使其能够将参数传递给服务器端 PHP,然后返回到调用 js 函数

编辑:如果有一种方法可以使用服务器端 javascript 而不是 PHP,那就更好了,因为脚本已经用 JS 编写,除非必要,否则我不想用 PHP 重写。

P粉593649715
P粉593649715

全部回复(1)
P粉129168206

我是如何解决类似问题的 JS

let formData = new formData();
    formData.append("nameOfFunction","function you want to call");
    formData.append("variableA","some value");
fetch("phpFileName.php"{body: formData,method: POST})
    .then((response)=>response.text)
    .then((data)=>{
        //do whatever
    })

PHP

$nameOfFunction = $_POST["nameOfFunction"];  // unsure past this point
echo "
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!