简体   繁体   中英

JQuery how to know when a new message is received?

Im using the follow javascript in messages page, is it possible to play a sound when a new message is received? Be aware that i don't want to play a sound for each request but only when a new message is added in the page.

function homeAjax() {
  $.ajax({
    url : 'subHome',
    success : function(data) {
      $('#result').html(data);
    }
  });      
}

var intervalId = 0;
intervalId = setInterval(homeAjax, 3000);

My MVC controller (subHome) returns all messages using ModelAndView.

maybe it will help.

<script type="text/javascript">
  var datLength = 0;
  function homeAjax() {
    $.ajax({
        url : '/data',
        contentType : "application/json",
        dataType : 'json',
        success : function(data) {

           if(data.length > datLength){
               console.log(data.length);
               datLength = data.length;
               /*jquery audio play*/
           }else{
               console.log("no play");
           }
        }
    });

    } 
 </script>

Show Console

在此处输入图片说明

Use an <audio> tag:

<audio id="myAudio" src="path/to/sound.mp3">

Then whenever you need to play the clip, use:

<script>
document.getElementById("myAudio").play();
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM