首页 > 解决方案 > Ajax 结果用作 mysql 查询约束

问题描述

我每 60 秒使用 ajax 显示一些数据库数据,如下所示:

 $(document).ready(function(){
        function getData(){
           $.ajax({
                type: 'GET',
                url: 'data.php',
                success: function(data){
                    $('#output').html(data);
            });
        }

        getData();
        setInterval(function () { getData();  }, 60000);  // it will refresh your data every 1 sec

    });

data.php文件有一个类似的查询:

$sql = "select * from orders where time > date_sub(now(), interval 1 minute) ORDER BY id DESC";

如何记录 ajax 检索到的最后一个间隔并将其传递到查询中,以便它只显示前一个 ajax 结果 + 60 秒之间的记录?

我担心如果某处有延迟,它可能会省略一些记录。

标签: jquerymysqlajax

解决方案


我最终以 json 格式将数据从 php 传递到 ajax:

function getData() {
                        $.ajax({
                            type: 'GET',
                            url: 'data.php',
                            data: {lastID: lastID},
                            dataType: 'json',
                            success: function (data) {
                                lastID = data[0].id;
                                console.log(lastID);
                                $.each(data, function (i, item) {
                                    var $tr = $('<tr class="page-break">').append(
                                            $('<td>').text(item.id),
                                            $('<td>').text(item.name),
                                            $('<td>').text(item.details)
                                            ).appendTo('#output');
                                });

                                function isEmpty(el) {
                                    return !$.trim(el.html());
                                }
                                if (!isEmpty($('#output'))) {
                                    window.print();
                                }

                            }
                        });
                    }

在 php 中:

$lastID = $_GET['lastID'];
$sql = "select * from orders where id > ".$lastID." ORDER BY id DESC";

推荐阅读