You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JS向WordPress的PHP传参调用函数并返回结果(含Node.js替代方案)

解决方案

一、PHP端修改:单文件多函数调用的统一入口

要让单个PHP文件支持调用不同核心函数,需要添加一个请求分发逻辑,通过前端传递的参数判断要执行哪个函数,同时接收传入的计算数据。修改后的test.php如下:

<?php
// 核心计算函数(保留原有逻辑,仅通过入口暴露)
function doStuff($myarr) {
    $myarr2 = [];
    for ($x = 0; $x <= 10; $x++) {
        if(isset($myarr[$x])){ // 避免数组越界报错
            array_push($myarr2, $myarr[$x]);
        }
    }
    return $myarr2;
}

function doOtherStuff(){
    return "Hello World";
}

// 前端请求处理入口
header('Content-Type: application/json'); // 统一返回JSON格式
$response = ['status' => 'error', 'data' => '无效请求'];

// 获取前端传递的动作和参数
$action = $_REQUEST['action'] ?? '';
$params = $_REQUEST['params'] ?? [];

// 兼容POST方式传递的JSON数据
if(empty($params) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false){
    $params = json_decode(file_get_contents('php://input'), true);
}

// 根据动作分发调用对应函数
switch($action){
    case 'doStuff':
        $result = doStuff($params);
        $response = ['status' => 'success', 'data' => $result];
        break;
    case 'doOtherStuff':
        $result = doOtherStuff();
        $response = ['status' => 'success', 'data' => $result];
        break;
}

// 返回处理结果
echo json_encode($response);
?>

二、JavaScript端修改:传递参数+处理异步请求

原代码的问题在于没传参数,且异步请求的结果不能同步赋值。改用fetch(比XMLHttpRequest更简洁)实现参数传递和结果处理,修改后的myjavascript.js:

function test_test(){
    const staticPNVals = getStaticPN(); // 获取用户输入的计算参数

    // 发送POST请求到PHP后端
    fetch('test.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'doStuff', // 指定要调用的PHP函数名
            params: staticPNVals // 传递给函数的参数
        })
    })
    .then(response => response.json())
    .then(data => {
        if(data.status === 'success'){
            const ret_array = data.data;
            console.log("ret_array is ", ret_array);
            // 这里直接把结果传给BokehJS生成图形即可
        } else {
            console.error('请求失败:', data.data);
        }
    })
    .catch(error => {
        console.error('网络出错:', error);
    });

    // 调用doOtherStuff的示例(只需修改action)
    // fetch('test.php', {
    //     method: 'POST',
    //     headers: {'Content-Type': 'application/json'},
    //     body: JSON.stringify({action: 'doOtherStuff'})
    // })
    // .then(...)
}

// 模拟获取用户输入的函数(实际替换成你的输入获取逻辑)
function getStaticPN(){
    return [1,2,3,4,5,6,7,8,9,10,11,12];
}

三、本地测试+部署兼容方案

  • 本地测试:
    • 用PHP内置服务器:在项目目录执行命令 php -S localhost:8000,然后访问 http://localhost:8000/mypage.html
    • 确保所有文件(html、js、php)在同一目录,避免跨域问题
  • WordPress部署:
    • 把test.php放到WordPress主题目录或自定义插件目录,也可以用WP自带的admin-ajax.php作为统一入口(更符合WP规范):
      在主题functions.php或插件文件中添加:
      add_action('wp_ajax_doStuff', 'doStuff');
      add_action('wp_ajax_nopriv_doStuff', 'doStuff'); // 允许未登录用户访问(按需开启)
      add_action('wp_ajax_doOtherStuff', 'doOtherStuff');
      add_action('wp_ajax_nopriv_doOtherStuff', 'doOtherStuff');
      
      对应的JS请求地址改为 /wp-admin/admin-ajax.php,请求body不变

四、改用服务端JavaScript(Node.js)方案(复用原有JS逻辑)

如果不想重写计算代码,直接用Node.js做后端复用原有JS:

  1. 新建server.js:
const express = require('express');
const app = express();
app.use(express.json());

// 直接复用你的核心计算逻辑
function doStuff(myarr) {
    const myarr2 = [];
    for (let x = 0; x <= 10; x++) {
        if(myarr[x] !== undefined){
            myarr2.push(myarr[x]);
        }
    }
    return myarr2;
}

function doOtherStuff(){
    return "Hello World";
}

// 接口路由
app.post('/api/calculate', (req, res) => {
    const { action, params } = req.body;
    let result;
    switch(action){
        case 'doStuff':
            result = doStuff(params);
            res.json({status: 'success', data: result});
            break;
        case 'doOtherStuff':
            result = doOtherStuff();
            res.json({status: 'success', data: result});
            break;
        default:
            res.json({status: 'error', data: '无效动作'});
    }
});

// 启动本地服务
app.listen(3000, () => {
    console.log('服务运行在 http://localhost:3000');
});
  1. JS端请求地址改为 http://localhost:3000/api/calculate,逻辑和之前的fetch代码一致
  2. 部署时用PM2管理Node进程,配合Nginx做反向代理对接域名

内容的提问来源于stack exchange,提问作者mrblue6

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:53:22