变量永远不会从FETCH API到达PHP



我在HTML中有3个文件(HTMLJSPHP(,保存JavaScript 中名为DatosPaciente的变量中的信息

function Tomar_DATOS(){            
DatosPaciente={
id:document.getElementById("paciente_id").value,
fecha:document.getElementById("fecha").value
};}

然后,我在JS文件中使用一个名为Tiene_CCita_Hoy的函数

Tiene_Cita_Hoy(DatosPaciente)

JS文件中,我尝试使用Fetch API将信息发送到PHP的文件

function Tiene_Cita_Hoy(Datos){
console.log(Datos);//"{id: "8", fecha: "2020/09/03"}" here everything is fine
fetch('tiene_cita.php',{
method: 'POST',
body: Datos
})                           
.then(res => res.json()) 
.then(data => {                     
console.log(data); //to see the result
})
}        

然后在PHP文件中,然后尝试通过POST接收信息

$VALOR_id_paciente=$_POST['id']; 
$VALOR_fecha=$_POST['fecha'];

然后我分配这些值​​到查询

$SQL="SELECT * FROM vhsagenda WHERE PACIENTE='".$VALOR_id_paciente."' AND FECHA='".$VALOR_fecha."'";
echo json_encode($SQL);//just to see what information have

但结果总是:SELECT * FROM vhsagenda WHERE PACIENTE='' AND FECHA=''

显然,信息从未到达PHP文件

我已经为这个方法找到了一些合适的方法。您需要先创建一个对象,然后将其传递给"for循环"。它将生成这样的字符串,例如(test=123&test_two=444(

async function catch_something(url, bodyContent = {test: 123, test_two: 444}){
let bodyContent_string = '';
if(bodyContent instanceof Object){
for(const form_key of Object.keys(bodyContent)){
if(form_key != Object.keys(bodyContent)[Object.keys(bodyContent).length - 1]){
bodyContent_string += `${form_key}=${bodyContent[form_key]}&`;
}else{
bodyContent_string += `${form_key}=${bodyContent[form_key]}`;
}
}
}
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyContent_string
}).catch((error) => {
console.error('Error:', error);
});
if(!response.ok){
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}

您应该将参数作为URL编码的字符串发送。

function Tomar_DATOS(){            
DatosPaciente = 'id=' + encodeURIComponent(document.getElementById("paciente_id").value) + '&fecha=' + encodeURIComponent(document.getElementById("fecha").value);
}

您已经向body参数传递了一个普通对象,但fetch不知道该如何处理该数据类型(因此它将其转换为无用的字符串"[object Object]"(。

您应该传递一些fetch知道如何转换为PHP支持的东西。

例如FormData对象。

DatosPaciente = new FormData(document.getElementById("form_containing_your_inputs"));

最新更新