doupin5667 2016-03-24 12:23
浏览 69

当数据库中存在新行时自动更新div

I am trying to retrieve all rows that are present within a table before the time the person has visited the page and there after update the div with any rows of data that has been added to the table since the user has been on the page.(Something like Whatsapp where the entire convo is visible and new messages get added to the bottom).

This is what I have so far using Ajax but I have no clue where I am going forward from this stage. It currently brings up only the newest record (IF I SET THE TIMESTAMP MANUALLY IN THE SECOND FILE) but not all the other records before it. Ideally I should work by posting the time to the second file.

How could I modify my code to get the functionality I desire?

Display (autoload.php)

var time = (new Date).getTime();
var interval = 1000;  // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
    $.ajax({
            type: 'POST',
            url: 'autoload2.php',
            dataType: 'json',
            data: 'time='+time,
            success: function (data) {
                $('.inner').append(data);
            },
            complete: function (data) {
                setTimeout(doAjax, interval);
            }
    });
}
setTimeout(doAjax, interval);

Get data (autoload2.php)

$time = $_POST['time'];
$results = mysql_query("SELECT post_name FROM posts WHERE postime > $time limit 1");
$row = mysql_fetch_assoc($results);
$res = $row['post_name'];
echo json_encode($res);

Note: The time being used to query above doesn't work, only when it is hardcoded with the timestamp.

  • 写回答

1条回答 默认 最新

  • dongshedan4672 2016-03-24 12:33
    关注

    I think you need to move

    var time = (new Date).getTime();
    

    to your function

    Because your time variable not changed

    var interval = 1000;  // 1000 = 1 second, 3000 = 3 seconds
    function doAjax() {
        var time = (new Date).getTime();
        $.ajax({
            type: 'POST',
            url: 'autoload2.php',
            dataType: 'json',
            data: 'time='+time
        }).done(function(response){
            console.log(response);
        });
    }
    
    setInterval(doAjax, interval);
    

    In php:

    $data = Array('name' => 'name of last row');
    header('Content-Type: application/json');
    echo json_encode($data);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据