进一步解释:
这是我的AJAX:
$(document).ready(
function loadAll (param) {
$.ajax({
url: 'functions.php',
type: 'POST',
dataType: 'JSON',
data: {task: "load", last_id: param},
success: function(data) {
$.each(data, function(i, attr) {
$("#result").append("<tr><td style='width:300px;'>" + attr.actor_id + "</td><td style='width:300px;'>" + attr.first_name + "</td>");
})
}
})
});
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
//Perform the loadAll() function using the last ID of the last query performed
//and then appending it to the #result
}
});
在这里,我基本上发送了一个请求,并将其附加到我的html中的#result
。然后,当用户向下滚动时,我希望函数发送上次执行的查询的last_id
,并检索一个带有返回的新项的新查询。
这是我的PHP:
if (isset($_POST['task']) && $_POST['task'] == "load") {
$last_id = isset($_POST['last_id'] ) ? (int)$_POST['last_id'] : 0;
$stmt = $connection->prepare("SELECT * FROM actor WHERE actor_id > (?) ORDER BY actor_id LIMIT 0, 30");
$stmt->bind_param('i', $last_id);
$stmt->execute();
$result = $stmt->get_result();
$encode[] = array();
while( $row = $result->fetch_assoc() ) {
$encode[] = $row;
}
echo json_encode($encode);
}
此查询检查是否设置了"last_id",如果没有,则将last_id设置为0。这很好用。
这是我的HTML(如果重要的话):
<div class="container">
<h1>Making an infinite scroll</h1>
<p>Load posts below:</p>
<div id="result"></div>
</div>
问题:如何使用AJAX使用查询的最后一个id进行查询,然后使用最后一个id进行另一个查询
这是我设想的一个程序:
1-POST请求,返回第一个查询[aactor_id为0,30],并将其附加到#result
2-将查询的最后一个id保存到变量中
3-如果用户向下滚动到页面末尾,则使用最后一个查询的最后一个id执行另一个查询[aactor_id为30到60]的actors,然后将其附加到#resultdiv。
如有任何帮助,我们将不胜感激。
您可以将最后提取的id与查询结果一起发送
while( $row = $result->fetch_assoc() ) {
$encode[] = $row;
}
$last_id = $encode[count($encode)-1]['actor_id'];
echo json_encode( array('encoded' => $encode, 'last_id' => $last_id) );
然后在客户端(你的jquery代码),你只需要这样做smth:
var last_id = 0;
function loadAll (param) {
$.ajax({
url: 'functions.php',
type: 'POST',
dataType: 'JSON',
data: {task: "load", last_id: param},
success: function(data) {
results = data.encoded;
last_id = data.last_id;
$.each(results, function(i, attr) {
$("#result").append("<tr><td style='width:300px;'>" + attr.actor_id + "</td><td style='width:300px;'>" + attr.first_name + "</td>");
})
}
})
}
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
loadAll(last_id);
//Perform the loadAll() function using the last ID of the last query performed
//and then appending it to the #result
}
});
我不确定我的问题是否答对了,但我想这是解决你问题的可能办法。
PS:
SELECT * FROM actor WHERE actor_id > (?) ORDER BY actor_id LIMIT 0, 30
你为什么不像那样做,有什么具体的原因吗
SELECT * FROM actor ORDER BY actor_id LIMIT (?), 30
我不完全理解你的问题,所以你可能需要扩展,因为它不清楚。
但是,您确实存在语法错误。
如果"last_id"是POST请求,那么它就是GET请求。
应该是这样的:
(isset($_POST['last_id']) && $_POST['last_id'] >= 1) ? $last_id = $_POST['last_id'] : $last_id = 0;