dreljie602951 2013-07-10 08:30
浏览 53
已采纳

仅在有新数据时重新加载div

If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...

<script type="text/javascript">
    function dispMsg() {
        $("#displayMessage").load('load.php');
        var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
        $("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
    }
    setInterval (dispMsg, 2500);
});
</script>

<div id="displayMessage"></div>

and here is the load.php:

$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
    $id = $result['id'];
    $from = $result['user_01'];
    $to = $result['to_usr'];
    $message = $result['message_01'];
    $date = $result['date_send'];

    echo "<span class='from'> $from </span>" 
      . "<span class='message'> $message </span> <br/>";
}
  • 写回答

3条回答 默认 最新

  • dongzhao4036 2013-07-10 09:27
    关注

    use the parameters and call back of $.load()

    $.load(url, {param1:value, param2:value}, function(result){ 
        if(result >5){ 
         //do something
        }
    )
    

    Example:

    <?php
    
    if($_REQUEST['action'] == 'check'){
        if($_REQUEST['lastId'] < 5 ){
            echo $_REQUEST['lastId']+1;
            die;
        }
    }
    
    if($_REQUEST['action'] == 'load'){
        echo 'some conntent!';
        die;
    }
    
    ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>    
    <script type="text/javascript">
    $(document).ready(function(){
        var lastId = 0;
        function dispMsg() { 
            $.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
    
                if(responce !== 0){
                    alert(responce);
                   $('#displayMessage').load('tmp.php', {action:'load'});
                }
            });
    
        }
        setInterval (dispMsg, 2500);
    });
    </script>
    
    <div id="displayMessage">1</div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?