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

使用fetch()将GET请求转换为POST请求的实现方法

转换GET请求为POST请求的解决方案

前端JavaScript修改

将原GET请求改为POST请求,需指定请求方法、设置正确请求头,并在请求体中传递参数:

function fetchData() {
    // 构造表单格式的请求参数
    const formData = new URLSearchParams();
    formData.append('action', 'submit');
    formData.append('data', encryptedFormValue);

    return fetch('dataProcessing', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData
    })
    .then((response) => response.json())
    .catch(error => {
        console.log(error, 'warn');
    });
}

如果偏好JSON格式传递参数,可使用以下写法:

function fetchData() {
    return fetch('dataProcessing', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'submit',
            data: encryptedFormValue
        })
    })
    .then((response) => response.json())
    .catch(error => {
        console.log(error, 'warn');
    });
}

后端PHP修改

对应前端的参数传递方式,调整后端代码以从POST请求中获取参数:

适配表单格式参数

直接将$_GET替换为$_POST即可:

} else if ($_POST["action"] == "submit") {
    echo '{"response": "' . processData($_POST["data"]) . '"}';

适配JSON格式参数

若前端用JSON传递参数,需先解析请求体:

} else {
    $input = json_decode(file_get_contents('php://input'), true);
    if ($input["action"] == "submit") {
        echo '{"response": "' . processData($input["data"]) . '"}';
    }
}

额外注意事项

  • 确保processData函数逻辑无需调整,能正常处理传入的参数。
  • 若网站启用CSRF防护,需在请求中携带CSRF令牌(可放在请求头或表单参数里),进一步强化安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:51:24