[英]The variables never reach PHP from the FETCH API
我在变量中的HTML保存德信息在JavaScript中称为DatosPaciente有3个文件(HTML,JS和PHP)
function Tomar_DATOS(){
DatosPaciente={
id:document.getElementById("paciente_id").value,
fecha:document.getElementById("fecha").value
};}
然后我在JS文件中使用一个名为Tiene_Cita_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();
}
您已将一个普通对象传递给body
参数,但fetch
不知道如何处理该数据类型(因此它将其转换为无用的字符串"[object Object]"
)。
你应该传递一些 fetch 知道如何转换成 PHP 支持的东西。
例如一个 FormData 对象。
DatosPaciente = new FormData(document.getElementById("form_containing_your_inputs"));
您应该将参数作为 URL 编码的字符串发送。
function Tomar_DATOS(){
DatosPaciente = 'id=' + encodeURIComponent(document.getElementById("paciente_id").value) + '&fecha=' + encodeURIComponent(document.getElementById("fecha").value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.