javascript - 无法显示获取参数
问题描述
我正在尝试显示获取的参数。从 fetch 我调用一个 php 脚本传递我想要显示的参数。
JavaScript 代码:
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;
let respuesta = fetch(fichero, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'nom=tp_curso&versio=vr_curso&programa=pr_curso&fitxers=fp_curso&
&fitxers=fp_curso&videos=vp_curso&ncurs=curso_actualizar',
headers: {"Content-type": "application/text; charset=UTF-8"}
})
.then(respuesta => respuesta.text())
.then(respuesta => {
alert(respuesta);
})
.catch(error => alert("Se ha producido un error: " + error));
php代码:
$this -> n_curso = $_POST["nom"];
$this -> titulo_curso = $_POST["versio"];
$this -> version_curso = $_POST["programa"];
$this -> programa_curso = $_POST["fitxers"];
$this -> dir_ficheros_curso = $_POST["videos"];
$this -> dir_videos_curso = $_POST["ncurs"];
$this -> params[0] = $this -> n_curso;
$this -> params[1] = $this -> titulo_curso;
$this -> params[2] = $this -> version_curso;
$this -> params[3] = $this -> programa_curso;
$this -> params[4] = $this -> dir_ficheros_curso;
$this -> params[5] = $this -> dir_videos_curso;
print_r($this -> params);
我显示的是一个空数组:
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
)
我读了这篇文章,但我无法解决这个问题。
我做错了什么?
谢谢
解决方案
您的参数对象文字包含headers
两次键,它采用后一个值(不幸的是不再是语法错误)。您正在发送application/text; charset=UTF-8
而不是application/x-www-form-urlencoded
for Content-Type
,因此 PHP 不会像您期望的那样解析参数。
要修复它,请使用
fetch(fichero, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: '…',
})
.then(respuesta => respuesta.text())
.then(respuesta => {
alert(respuesta);
})
.catch(error => alert("Se ha producido un error: " + error));
另请注意,您body
当前是硬编码字符串,未考虑变量。为此,您需要
使用模板字符串(或字符串连接)自己转义值:
body: `nom=${encodeURIComponent(tp_curso)}&versio=${encodeURIComponent(vr_curso)}&…`,
使用一个
URLSearchParams
对象:body: new URLSearchParams({nom: tp_curso, versio: vr_curso, …}),
使用一个
FormData
对象。<form>
如果您对所有输入元素都有 a 并且每个元素<input>
都有适当的属性,这是最简单的name
(就像您在本机提交表单时使用的一样,没有任何 XHR/fetch
):body: new FormData(document.getElementById('accion_form')),
推荐阅读
- python-3.x - 在路由方法中调用函数的最佳实践
- r - 根据条件从上一组中选择值
- c# - 如何在 Mac 上的 C# 中区分进程的用户
- google-fit - 我可以在不开发 WearOS 配套 APP 和 Google Fit APP 的情况下使用 Google Fit API 吗?
- node.js - 使用 SCP 的 GitLab CI
- node.js - OPC-UA 服务器能否覆盖连接客户端的超时和其他参数?
- sql - 如何按日期获取价格总和并获得空结果?
- css - 使用 flexbox,我如何创建这个简单的应用程序页面登录屏幕?
- angular - 需要在 Angular 的 mat-dialog 上显示额外的数据
- c++ - 在编辑器属性更改中未调用 UWidget::SynchronizeProperties()