AJAX SET INTERVAL

时间:2014-10-12 14:08:01

标签: php jquery ajax

我想在表中获取最新的post_id而不刷新它,但问题是每当用户向数据库插入一个值时,它会无限地回显最后一个post_id。我希望它只回应一次。但是我仍然希望从表中获得最新的post_id。

这是我的主要php:

<div id = "this_div">
        <?php
            include 'connect.php';
            session_start();
            $query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
            $execute_query = mysqli_query($con,$query);
            while($row = mysqli_fetch_assoc($execute_query))
            {
                $get_this_id = $row['post_id'];
                echo $get_this_id."<br>";
            }
            $_SESSION['get_this_id'] = $get_this_id;
        ?>
</div>

这是我的jQuery ajax:

 <script>
            var refreshId = setInterval(function(){
            compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
                $.ajax({
                url: 'another_file.php',
                data: {},
                success: function(data)
                {
                    if(compare_session != data)
                    {
                        $('#this_div').text($('#this_div').text()+data);
                    }
                }
                });
            },400);
</script>

这是另一个文件的另一个文件

<?php
  include 'connect.php';
  session_start();
  $query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
  $execute_query = mysqli_query($con,$query);
  if($row = mysqli_fetch_assoc($execute_query))
  {
    echo $get_this_id = $row['post_id'];
  }
?>

1 个答案:

答案 0 :(得分:1)

您没有更新compare_session变量,它始终保持初始值。所以在成功回调函数中更新它

compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
    $.ajax({
        url: 'another_file.php',
        data: {},
        success: function (data) {
            if (compare_session != data) {
                $('#this_div').text($('#this_div').text() + data);
            }
            compare_session = data;
        }
    });
}, 400);