想要那种有提示声音的网站吗?我教你怎么做!

您有新的外卖订单请及时查收!

熟悉不能再熟悉的声音了,今天小编就做了这样一个网站的提示新订单的功能,接下来就教你怎么玩转这个小功能!

首先我们前端的代码是这样写的:

var playSound = function () { var borswer = window.navigator.userAgent.toLowerCase(); if ( borswer.indexOf( "ie" ) >= 0 )
 { //IE内核浏览器
 var strEmbed = '<embed name="embedPlay" src="/public/Mp3/newOrder.mp3" autostart="true" hidden="true" loop="false"/>'; if ( $( "body" ).find( "embed" ).length <= 0 ) $( "body" ).append( strEmbed ); var embed = document.embedPlay; //浏览器不支持 audion,则使用 embed 播放 embed.volume = 100;
 } else { //非IE内核浏览器
 var strAudio = "<audio id='audioPlay' src='/public/Mp3/newOrder.mp3' hidden='true'>"; if($("#audioPlay").length<=0){
 $( "body" ).append( strAudio );
 } var audio = document.getElementById( "audioPlay" ); //浏览器支持 audio
 audio.play();
 }
}

上面这些是播放媒体声音的功能,下面介绍怎么去后端请求数据了

/**新订单*/function getNewOrder(){
 $.post("{:U('Msg/newOrder')}", {}, function(res) { if (res) {
 playSound();
 $.post("{:U('Msg/msgDetail')}", {id:res.id}, function(res) {});
 }
 });
}/**定时器大家都懂吧*/window.setInterval("getNewOrder()",3000);

以上是做ajax的轮询操作,当然你做成websockt也是可以的,本文就作为一个抛砖引玉的作用吧。

后端的话,可以去数据库查询,也可以在前端做好redis缓存,或者其他缓存,然后从缓存里面获取数据等等都是可以的!

是不是很简单,快去尝试一下吧!


猜你喜欢

转载自blog.51cto.com/13284080/2331193