P粉6429198232023-08-14 11:25:25
To update multiple parts of the page with data from different queries, you can modify the JavaScript code and PHP code accordingly. Here's what you can do:
Modify your PHP script (caricaNumeri.php) to return a JSON object containing the results of both queries:
php
<?php include '../config.php'; // 检查连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $response = array(); $query = "SELECT COUNT(id) AS totale FROM indirizzi"; $risultato = $conn->query($query); if ($risultato->num_rows > 0) { // 输出每一行的数据 while($row = $risultato->fetch_assoc()) { $response["totale"] = $row["totale"]; } } else { $response["totale"] = "Ancora nessuna per ora!"; } $query = "SELECT COUNT(stato) AS daConsegnare FROM indirizzi WHERE stato = ''"; $risultato = $conn->query($query); if ($risultato->num_rows > 0) { // 输出每一行的数据 while($row = $risultato->fetch_assoc()) { $response["daConsegnare"] = $row["daConsegnare"]; } } else { $response["daConsegnare"] = "Ancora nessuna per ora!"; } echo json_encode($response); ?>
Modify your JavaScript code to handle multiple data fragments returned by the PHP script:
javascript
function caricaNumeri() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const data = JSON.parse(this.responseText); document.getElementById("nLettere").innerHTML = data.totale; document.getElementById("daConsegnare").innerHTML = data.daConsegnare; } }; xhttp.open("GET", "script/caricaNumeri.php", true); xhttp.send(); } setInterval(function(){ caricaNumeri(); }, 1000); // 每秒更新一次(根据需要进行调整)
Update your HTML to include a placeholder for the second data:
html
<div id="nLettere"></div> <div id="daConsegnare"></div>
Now when you run the caricaNumeri function it will get the two data fragments from the server and update the corresponding parts of the page. Please adjust the interval (setInterval) according to how often you want the data to be updated.