播放通知声音用JavaScript
问题描述:
我有这个script
从中获取新邮件我database
播放通知声音用JavaScript
setInterval(function() {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
}
});
}, 2000);
我尝试将声音一旦新数据添加到database
添加到它,但是当我加入在script
以上,它起着audio
每2 seconds
(我想这是因为它在setInterval
)
setInterval(function() {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
var audio = new Audio('audio_file.mp3');
audio.play();
}
});
}, 2000);
所以请我问。只有当新数据添加到数据库时,我该如何播放声音?
答
缓存最后的response
并将其与新版本进行比较以确定是否播放音频文件。
var lastResponse = ''
setInterval(function() {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function(response) {
$(".msg_area").html(response)
if (lastResponse && response !== lastResponse) {
var audio = new Audio('audio_file.mp3')
audio.play()
}
lastResponse = response
}
});
}, 2000);
编辑:如果你想要的音频播放的第一次response
进来,从上面的代码中删除lastResponse &&
。
+0
非常感谢。这工作正常 –
答
首先,确保它起着因为setInterval()
你需要响应前后对比数据库中的信息的行NUM周期2s ..对我来说是简单的事情是通过它藏在里面<div>
在您的最后一条消息
setInterval(function() {
var message_num = // get the number from the last message
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msg_area").html(response);
var new_message_num = // get the number from the last message after response
if(new_message_num > message_num){
var audio = new Audio('audio_file.mp3');
audio.play();
}
}
});
}, 2000);
是否每次都有“响应”来临? –