php - 使用预设值初始化第一个 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。
解决方案
$lastID
你的变量来自哪里,它是如何定义的?
看起来您没有从$_GET
数组中获得正确的值。
为了解决这个问题和你遇到的 sql 注入问题,你应该做的是切换到准备好的语句:
$sql = "select * from oders where id > ? ORDER BY id DESC";
并在执行查询之前/期间绑定$_GET['lastID']
到占位符(取决于您使用的是 mysqli 还是 PDO)。
推荐阅读
- mysql - 查找仅购买特定产品且未购买任何其他产品的客户(MySQL)
- node.js - 是否可以向 nodemon 添加类似“rs”的命令?
- linux - Linux 内核模块:向 sysfs 公开 I²C 寄存器
- awk - 如何过滤掉 ./gradlew project:dependencies 命令的某个部分?(第 3 版)
- reactjs - React Context - 使用 Provider 和 ContextName.Provider 这样的上下文
- reactjs - 提交后如何更改道具并将值传递给另一个组件?
- javascript - Etch-a-Sketch 游戏 - 网格着色
- forms - 更改重力形式下拉悬停的背景颜色
- ios - ObservedObject 没有注意到 ObservableObject Array 的变化
- react-native - 反应导航导航到嵌套屏幕仅在访问父级后才有效