如何使用AJAX每隔一段时间将数据从SQL服务器刷新到PHP页面



如何使用AJAX从"温度;每隔几分钟更新一次,只在网页中更新该数字,而不刷新页面?

index.php 的一部分

<!-- Top Container -->
<section class="top-container">
<div class="top-box top-box-a">
<p class="values"><i class="fas fa-thermometer-three-quarters"></i><br>
<?php 
include 'sql_nowTemp.php'
?>°C</p>
<h3 class="label">Temperature</h3>
</div>
<div class="top-box top-box-b">
<p class="values"><i class="fas fa-tint"></i><br>
<?php 
include 'sql_nowHumid.php'
?>%</p>
<h3 class="label">Humidity</h3>
</div>
<div class="showcase"><div class="graph" id="line_chart"><h3>Loading...</h3></div>
</div>
</section>

sqlnowTemp.php

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT temperatur FROM setest ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $english_format_number = number_format($row["temperatur"], 2);
}
} else {
echo "--.--";
}
mysqli_close($conn);
?>

还有一个额外的问题:是否可以对多个请求/号码使用一个全局计时器?

继之前关于Server Sent Events的评论之后,我很快拼凑出了一个演示,可以很容易地进行修改以满足您的需求。

答案的PHP部分是使用javascript连接到的端点。PHP脚本在一个无限循环中运行,每5秒(或任何时间(就会查询一次数据库。在index.php文件中的Javascript代码连接sonce,然后连接来自服务器的消息的listens。你如何处理这些消息完全取决于你自己,以满足你的应用程序的需求,在这里,它们只是写在屏幕上。

HTML(非常基本的客户端(

<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<title>Updates from mySQL server!</title>
</head>
<body>
<div id='results'></div>
<script>

const message=(data)=>{
let div=document.createElement('div');
div.textContent=data;
document.getElementById('results').appendChild( div )
}


let sse = new EventSource('sqlnowTemp.php');
sse.addEventListener('temperature-reading',e=>{
message(e.data);
console.info(e.type)
});
sse.addEventListener('error',e=>{
console.warn(e)
});
</script>
</body>
</html>

PHP服务器(sqlnowTemp.PHP(

<?php
# sqlnowTemp.php

error_reporting( E_ALL );

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Access-Control-Allow-Methods: GET');


# Add your db connection
/*

$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';

mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$db = $mysqli = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

*/
$sleep=5; # 5 seconds 
$evt='temperature-reading';


function sse( $evtname='sse', $data=null, $retry=1000 ){
if( !is_null( $data ) ){
echo "event:".$evtname."rn";
echo "retry:".$retry."rn";
echo "data:" . json_encode( $data, JSON_FORCE_OBJECT );
echo "rnrn";
}
}   

$id=23;# for demo only!!!



while( true ){
if( connection_status() != CONNECTION_NORMAL or connection_aborted() ) {
break;
}

# empty payload variable
$payload=[];



# construct your sql command and execute the query.
$sql='select `temperatur` from `setest` order by `id` desc limit 1';
# actually query the db and fetch the recordset
# and send as the $payload.
#
# here that process is emulated...
# $payload=$db->query( $sql )->fetch_all( MYSQLI_ASSOC );

$payload=array(
'id'            =>  $id++,
'temperature'   =>  mt_rand(50,80),
'sensor'        =>  'ok',
'error'         =>  'none',
'time'          =>  date( DATE_ATOM )
);

# call the function to echo the data 
if( !empty( $payload ) )call_user_func( 'sse', $evt, $payload );

# actually send the output by flushing output buffers
if( @ob_get_level() > 0 ) for( $i=0; $i < @ob_get_level(); $i++ ) @ob_flush();
@flush();


# wait for defined period before repeating loop
sleep( $sleep );
}   
?>

屏幕上的结果将类似于此:

{"id":23,"temperature":51,"sensor":"ok","error":"none","time":"2022-10-14T23:13:59+01:00"}
{"id":24,"temperature":68,"sensor":"ok","error":"none","time":"2022-10-14T23:14:04+01:00"}
{"id":25,"temperature":55,"sensor":"ok","error":"none","time":"2022-10-14T23:14:09+01:00"}
.......... etc

最新更新