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
相关产品推荐
相关产品推荐

