首页 > 解决方案 > 使用预设值初始化第一个 ajax 数据,然后从成功响应中传递它

问题描述

我如何才能lastID第一次使用值0初始化 in jquery,因为var lastID = 0;它不起作用。

我在 index.php 中有这个 ajax 脚本

<script>
        $(document).ready(function () {
            var lastID = 0;
            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>').append(
                                        $('<td>').text(item.id),
                                        $('<td>').text(item.name),
                                        $('<td>').text(item.details)
                                        ).appendTo('#output');
                            });



                    }
                });
            }


            getData();


            setInterval(function () {
                getData();
            }, 10000);  // it will refresh your data every 10 seconds

        });
    </script>

这是url: 'data.php'

$sql = "select * from oders where id > ".$lastID." ORDER BY id DESC"; ... echo json_encode($dataArray);

使用此查询,我得到 0 个结果,并且在控制台 ( console.log(lastID);) 中我没有数据。

如果我像这样更改查询:

$sql = "select * from oders where id > 0 ORDER BY id DESC";

console.log(lastID);我得到正确的最后一个ID。在 html 中,我得到了正确的数据,并且每 10 秒它会一遍又一遍地添加相同的结果。

我不知道如何将 lastID 第一次初始化为 0(或数据库中的最后一个 ID),并且每 10 秒刷新一次,从 ajax 成功数据中获取最后一个 ID。

标签: phpjqueryjsonajax

解决方案


$lastID你的变量来自哪里,它是如何定义的?

看起来您没有从$_GET数组中获得正确的值。

为了解决这个问题和你遇到的 sql 注入问题,你应该做的是切换到准备好的语句:

$sql = "select * from oders where id > ? ORDER BY id DESC";

并在执行查询之前/期间绑定$_GET['lastID']到占位符(取决于您使用的是 mysqli 还是 PDO)。


推荐阅读