我有以下代码用于自动刷新行。我想只在我的数据库中有传入的新条目时播放声音警报。
新行更新,警报消息运行,但无论数据库条目是否为新,通知声音都会自动重播。我很难确定:
以下是我的代码:
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<!-- New Posts -->
<div id="newposts"></div>
</body>
</html>
使用findBootstrapEnvironment函数JavaScript代码:
<script language="javascript">
var env = findBootstrapEnvironment();
var audioElement = new Audio();
function playAlert(ignore_checked) {
if (ignore_checked || (document.getElementById('play_sound') && document.getElementById('play_sound').checked)) {
if (!document.contains(audioElement)) {
document.body.appendChild(audioElement);
}
if (audioElement.canPlayType("audio/mp3")) {
audioElement.src = 'notify.mp3';
} else if (audioElement.canPlayType("audio/wav") || audioElement.canPlayType("audio/x-wav")) {
audioElement.src = 'notify.wav';
}
if (audioElement.currentTime) {
audioElement.currentTime = 0;
}
audioElement.play();
}
}
function updateHistory() {
var datastring = '';
jQuery.ajax({
type: 'GET', url: 'connect.php', data: datastring,
success: function (server_response) {
if (server_response != '1') {
$('#newposts').html(server_response);
if (server_response.length = 0) return;
document.getElementById('updatewarning').innerHTML = '<p><strong>There have been updates to this page.</strong> Please view the updates.</p>';
document.getElementById('updatewarning').style.display = 'block';
var title = document.title;
title = title.replace("UPDATED - ", "");
document.title = "UPDATED - " + title;
playAlert();
}
}
});
setTimeout("updateHistory()", 20000);
}
updateHistory();
function findBootstrapEnvironment() {
var envs = ['xs', 'sm', 'md', 'lg'];
var $el = $('<div>');
$el.appendTo($('body'));
for (var i = envs.length - 1; i >= 0; i--) {
var env = envs[i];
$el.addClass('hidden-'+env);
if ($el.is(':hidden')) {
$el.remove();
return env;
}
}
}
</script>
PHP文件代码:我创建了带有单个表(事件)的数据库
<?php
$host="localhost"; //Mysql Database Host Address
$username="root"; //Database Username
$pass=""; //Database Password
$dataname="testdb"; //Database Name
$connect = mysqli_connect($host, $username, $pass)
or die("Could not connect: " . mysql_error());
mysqli_select_db($connect, $dataname) or die(mysqli_error($con));
$sql = "SELECT * FROM events ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
print "
<div><ul>";
while($row = mysqli_fetch_array($result))
{
echo "<li><span>" . $row['time'] . "</span></li>"; // Things that you want to fetch
}
echo "
</ul></div>";
?>