无法显示获取参数

Can't display fetch params

我正在尝试显示提取的参数。从 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] => 
   )

我读了这个 post 但我无法解决问题。

我做错了什么?

谢谢

您的参数对象文字 (which )。对于 Content-Type,您发送的是 application/text; charset=UTF-8 而不是 application/x-www-form-urlencoded,因此 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 当前是硬编码字符串,未考虑变量。为此,您需要

  • 自己使用 escaping the values 模板字符串(或字符串连接):

    body: `nom=${encodeURIComponent(tp_curso)}&versio=${encodeURIComponent(vr_curso)}&…`,
    
  • 使用一个 URLSearchParams 对象:

    body: new URLSearchParams({nom: tp_curso, versio: vr_curso, …}),
    
  • 使用 FormData 对象。如果所有输入元素都有一个 <form> 并且每个 <input> 都有适当的 name 属性(就像您在本地提交表单时使用的一样,没有任何 XHR,这是最简单的/fetch):

    body: new FormData(document.getElementById('accion_form')),