我想进行 2 个 Fetch API 调用,将数据从 JS 文件传输到 PHP 文件。第一个调用是有条件的,并传输一组数据(在我的 PHP 文件中已正确处理) 第二个 API 调用是一种计时器(使用 setInterval 函数),我想用它来检查客户端是否仍在浏览器上(是的,这是最终目标!)。这两个调用工作正常(不会出现错误)并且可以从第一个数组中正确获取数据)。问题是我不知道如何在 PHP 文件的变量中单独获取计时器数据(接下来我将把它推入数组)!你能指点一下吗(我还是 Fetch 的初学者..)
这是我的 JS 文件中的代码
第一次通话
if(...Button pressed...){
fetch("cart.php",{
"method":"POST",
"Headers":{
"content-type":"application/json; charset=utf-8"
},
"body":JSON.stringify(arrayOrderedProducts)
})
.then(function(response){
return response.text()
})
.then(function(data){
console.log(data)
})
}
第二次通话
setInterval(()=>{
timer+=1
},1000)
function checkConnection(){
fetch ("cart.php",{
method:"Post",
body :timer
})
.then(
response=>{
return response.text()})
.then(
response=>{
console.log(timer)
})
.catch(
error=>{
console.log(error)
})
}
let intervalConCheck = setInterval(()=>checkConnection(),1000)
这是我的 PHP 文件中的代码
<?php
if(isset($_POST)){
$data = file_get_contents("php://input");
$orders = json_decode($data);
...rest of code that retrieve data in arrayOrderedProducts...
}
?>
要实现您想要的效果,您需要修改 JavaScript 代码,以便与第一次调用分开发送计时器值。以下是如何构建 JavaScript 代码的示例:
let arrayOrderedProducts = [...] // Your array of ordered products
let timer = 0; // Initialize timer
// First Call
if (... /* Button pressed condition */) {
fetch("cart.php", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({ orders: arrayOrderedProducts, timer: timer })
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
}
// Second Call (Timer)
setInterval(() => {
timer += 1;
// Update the timer value in the PHP file
fetch("cart.php", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: timer.toString()
})
.then(response => response.text())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
}, 1000);
在 PHP 文件中,您可以分别处理从两个调用接收到的数据:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = file_get_contents("php://input");
// Check if the data is JSON (from the first call)
$jsonData = json_decode($data, true);
if ($jsonData !== null && isset($jsonData['orders'])) {
$orders = $jsonData['orders'];
// Process the $orders array here
// ...
// Example: Send a response back to the client
echo "First call data processed successfully";
}
// Check if the data is plain text (from the second call)
else {
$timer = intval($data);
// Process the $timer value here
// ...
// Example: Send a response back to the client
echo "Second call data processed successfully";
}
}
?>
这样,您可以区分第一次调用中发送的数据(包含订购产品的数组)和第二次调用中发送的数据(包含计时器值)。根据您的具体要求调整 PHP 文件中的处理逻辑。