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

时间:2013-07-10 08:30:30

标签: php ajax

如果我创建这样的脚本,那么它将每2.5秒重新加载一次div。我想要一个只显示新数据的脚本,如果没有新数据则不需要重新加载......

<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>

这是 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 个答案:

答案 0 :(得分:0)

您可以使用每个请求发送最后一条消息ID。如果查询的最后一条消息大于发送的id,请发送响应。否则什么都不发送。

function load_messages(){
    var last = $('#messagewindow p:last').attr('id');
    $.ajax({
        url: base_url + "load.php",
        type: "POST",
    data: {
        last: last
    },
        cache: false,
        success: function(html){
          //insert message
        }
    });
}

您可以在HTML中将id作为id属性发送。聊天窗口中的每条消息都会作为段落发送,并带有一些消息ID,例如id="133"

答案 1 :(得分:0)

扩展@PédeLeão的解决方案,这里更简单:

<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
    $msg = $result->fetch_assoc();

    if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
        echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
    }
}

在客户端:

function dispMsg() {
    var last = $('#displayMessages span.from').attr('id');
    $.get(baseUrl + '/load.php', { last: last }, function(result) {
         if (result) {
             $('#displayMessages').html(result);
         }
    });
}

请注意,这会替换displayMessages中的所有内容。

答案 2 :(得分:0)

使用参数并回调$.load()

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

示例:

<?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>