doushua7737 2018-07-20 08:53
浏览 72
已采纳

使用预设值初始化第一个ajax数据,然后从成功响应中传递它

How can I initialize the lastID in jquery only first time with the value 0 because var lastID = 0; does not work.

I have this ajax script in index.php

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

This is the url: 'data.php' :

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

With this query I get 0 results, and in console (console.log(lastID);) I have no data.

If I change the query like this :

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

In console.log(lastID); I get the correct last id. And in html I get the correct data and every 10 seconds it keeps adding same results over and over again.

I can't figure out how to initialize lastID first time as 0 (or the last ID in the database), and on every 10 seconds refresh, take the last ID from the ajax success data.

  • 写回答

1条回答 默认 最新

  • douzhang1955 2018-07-20 09:01
    关注

    Where does your $lastID variable come from, how is it defined?

    It looks like you are not getting the correct value from the $_GET array.

    What you should do to both solve that problem and the sql injection problem you have, is switch to a prepared statement:

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

    And bind $_GET['lastID'] to the placeholder before / during the execution of your query (depending on whether you are using mysqli or PDO).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵