您可以通过 JQuery 轮询每 x 秒调用一次的活动表到从活动表中读取的 PHP 脚本,这样您就可以检测用户是否按下了按钮。一个简单的方法是这样的:用户按下一个按钮 -> 你将活动发送到带有时间戳的活动表,所以你知道用户何时按下按钮(我们稍后会谈到)。您可以通过 JQuery 向 PHP 发送一个帖子,然后将其插入数据库中。活动表将包含:id (INT)、primary、auto_increment。button (INT) [The button id that was clicked] dateposted [timestamp] 现在,每次您使用 JQuery 和 PHP 轮询该表/调用该表时,您将轮询时间(重要)和按钮 id,我经常这样做:
客户端:(您可以像这样为每个按钮设置不同的 ID)
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php", function(buttonid){
if (buttonid == 1) /* Say he clicked the record button for example */
{
$("#recordbtn").css({"background-color":"#FF0000"}); /* Make the record button red */
}
});
}, 1000); // refresh every 1000 milliseconds
/* And this would poll every 1 second as it says above */
服务器端:(checkactivity.php)
<?php
checkactivity();
function checkactivity() {
$querystats = "SELECT activity.id, activity.buttonid, activity.dateposted FROM activity ORDER BY id DESC LIMIT 1";
$resultstats = mysqli_query($yourdbhandle,$querystats);
$num_stats = mysqli_num_rows($resultstats);
$rowactivity = mysqli_fetch_assoc($resultstats);
if($num_stats > 0) { /* If there was activity */
$activity_id = $rowactivity["id"];
$activity_date = $rowactivity["dateposted"]; //I can't indent this here for some reason.
$activity_buttonid = $rowactivity["buttonid"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time(); //The actual time in a timestamp
$timetoseconds = $actualtime - $timeactivity; //Actual time - timeactivity
if($timetoseconds < 6) { /* If the last activity was sent less than 6 seconds ago */
echo "$activity_buttonid"; //This would send the last clicked button id
}
}
}
?>
这不是最好的方法,而是一种简单的方法,最好的方法是使用 webSockets 或 node.JS 来避免一遍又一遍地轮询数据库,并且只有在服务器找到后才将结果发送给客户端更新。这是一个草稿,并简要说明了如何执行此操作。