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

fetch发送POST请求调用PHP脚本无法接收传递参数如何解决

问题排查

你的代码存在3个核心错误,逐一对应修复即可:

  • 错误1:重复定义headers字段,正确的表单提交头被覆盖
    你在fetch配置里先后写了两次headers,后定义的"Content-type": "application/text; charset=UTF-8"会覆盖之前正确的application/x-www-form-urlencoded头,PHP无法识别这种格式的请求体,自然无法解析出$_POST数组的内容。
  • 错误2:请求体参数没有插入变量值,全是固定字符串
    你直接把变量名写在了字符串里,JS不会自动解析变量,实际提交的nom值就是固定的tp_curso字符串,而非你提前取到的表单值;另外请求体里有多余的换行、空格、重复的&和重复的fitxers参数,也会导致参数解析异常。
  • 错误3:ncurs参数没有对应变量
    你提交的ncurs=curso_actualizar里curso_actualizar是固定字符串,如果你要传对应变量值,需要提前定义该变量取值。

修复后的JS代码

const fichero = "/proves/php/accion_formulario.php";

let tp_curso = document.getElementById("actualizar_nombre").value;
let vr_curso = document.getElementById("version_lenguaje").value;
let pr_curso = document.getElementById("programa_curso").value;
let fp_curso = document.getElementById("ficheros_curso").value;
let vp_curso = document.getElementById("videos_curso").value;
// 如果ncurs要传变量,在这里定义赋值,示例:
// let curso_actualizar = document.getElementById("对应元素ID").value;

let respuesta = fetch(fichero, {
    method: "POST",
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    // 用模板字符串插入变量值,清理多余符号
    body: `nom=${tp_curso}&versio=${vr_curso}&programa=${pr_curso}&fitxers=${fp_curso}&videos=${vp_curso}&ncurs=${curso_actualizar}`, 
})
.then(respuesta => respuesta.text())
.then(respuesta => {
    alert(respuesta); 
})
.catch(error => alert("Se ha producido un error: " + error));

优化建议

如果不想手动拼接表单字符串,可以直接用FormData对象,不需要手动设置Content-Type头,浏览器会自动处理,也能避免拼写错误:

const formData = new FormData();
formData.append('nom', tp_curso);
formData.append('versio', vr_curso);
// 依次添加其余参数即可

fetch(fichero, {
    method: 'POST',
    body: formData
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:15:01