Heim > Fragen und Antworten > Hauptteil
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)。