php 进行不同的API调用

3vpjnl9f  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(66)

我想做两个Fetch API调用来将数据从我的JS文件传输到我的PHP文件。第一个调用是有条件的,并传输一个数据数组(在我的PHP文件中得到了正确的处理)第二个API调用是一种计时器(使用setInterval函数),我想用它来检查客户端是否仍在浏览器上(是的,这是最终的目标!)。2个电话工作正常(没有得到错误,可以从第一个数组中正确获取数据)。问题是,我不知道如何在PHP文件中的变量中单独获取计时器数据(我下一步会把它推到数组中)!你能告诉我怎么做吗(我还是个初学者。)
下面是我的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...

}
?>

hxzsmxv2

hxzsmxv21#

为了实现你想要的,你需要修改你的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文件中的处理逻辑。

相关问题