首页 > 解决方案 > 无法显示获取参数

问题描述

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

我读了这篇文章,但我无法解决这个问题。

我做错了什么?

谢谢

标签: javascriptphpfetch-api

解决方案


您的参数对象文字包含headers两次键,它采用后一个值不幸的是不再是语法错误)。您正在发送application/text; charset=UTF-8而不是application/x-www-form-urlencodedfor 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')),
    

推荐阅读