dtsc14683 2016-02-04 19:09
浏览 63
已采纳

Jquery ajax如何更新html元素而不是每隔x秒监听更新?

Is there a way to check new updates in the database without using setInterval? The problem is that I want to update the video source in the video tag but if I check for update every second, then my video will keep refreshing. I just want the video to refresh if the database is updated. For example, If I have a cat video in the current_video column in database, then the cat video should play. Otherwise, if I update the video to dog video, only then will the video element change to dog video.

$.get("/musicmania/playing/getCurrentSongDir", function(data, status){
    setInterval(function(){
            $("#video").html("<source src='/musicmania/app/resources/"   
            + data + "' type='video/mp4'></source>");
    }, 500);
});
  • 写回答

1条回答 默认 最新

  • doucan4873 2016-02-04 19:43
    关注

    You can add if statement and check if old data and the new one are not equal then refresh the video. Your code will look something like this.

    var old_data='';
    $.get("/musicmania/playing/getCurrentSongDir", function(data, status){
       if( old_data != data ) {
           $("#video").html("<source src='/musicmania/app/resources/"   
            + data + "' type='video/mp4'></source>");
       }
       old_data = data;
    });
    

    If you want to do it via ajax technology you have to send request every 'x' seconds. But there is another technology called websockets. You can use websockets if you don't want to open connection to server side every 'x' seconds.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效