P粉6429198232023-08-14 11:25:25
要使用不同查詢的資料更新頁面的多個部分,您可以相應地修改JavaScript程式碼和PHP程式碼。以下是您可以執行的操作:
修改您的PHP腳本(caricaNumeri.php),以傳回包含兩個查詢結果的JSON物件:
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); ?>
修改您的JavaScript程式碼以處理PHP腳本傳回的多個資料片段:
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); // 每秒更新一次(根据需要进行调整)
更新您的HTML,包含第二個資料的佔位符:
html
<div id="nLettere"></div> <div id="daConsegnare"></div>
現在,當您執行caricaNumeri函數時,它將從伺服器取得兩個資料片段並更新頁面的相應部分。請根據您希望資料更新的頻率調整間隔時間(setInterval)。