php - 在 AJAX 中到达底部时无法加载更多数据
问题描述
我正在尝试SQL
在到达底部时加载更多数据,但是当我尝试使用此代码时,没有从SQL
.
如何向此代码添加无限滚动?
我尝试调试echo
$query
并得到
SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC LIMIT 4 OFFSET 10
我是对的query
,我还检查了控制台错误,但我什么也没得到,没有从 SQL 加载数据。
有人可以帮我解决这个问题吗?
var flag = 0;
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300)
{ //RUN when the page is almost at the bottom
flag += 4; //AUTO IN INCREMENT
$(document).ready(function () {
filter_data();
function filter_data() {
$.post(
"fetch.php",
{
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date'),
offset: flag,
limit: 4
}
)
.done(function (data) {
$('.filter_data').html(data);
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
});
}
});
这是PHP
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
if (empty($_POST['sort']) || $_POST['sort'][0] == "date") {
$query .= " ORDER BY pdt DESC";
} elseif ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") {
$query .= " ORDER BY prs " . $_POST['sort'][0];
}
if (!empty($_POST['offset']) && isset ($_POST['limit'])) {
$query .= " LIMIT ".$_POST['limit']." OFFSET ".$_POST['offset']."";
} else {
$query .=""; // in case it is not set
}
echo $query;
$stmt = $conn->prepare($query);
$params = array_merge($_POST['cate'], $_POST['brand'], $_POST['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
foreach ($result as $row) {
$parameter = $row['pid'];
$hashed = md5($salt . $parameter);
$output .= '<a href="/single_view.php?p=' . $parameter . '&s=' . $hashed . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
<div class="card border-0 small">
<img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
<h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . ' / ' . $row['mdl'] . '</h6>
<p class="card-text"><strong class="card-text text-dark text-truncate">₹ ' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
</div>
</div>
</a>';
}
} else {
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
有人可以帮我在滚动到底部时如何加载数据
在向滚动方法添加负载之前
$(document).ready(function () {
filter_data();
function filter_data() {
$.post(
"fetch.php",
{
action: 'fetch_data',
cate: get_filter('cate'),
brand: get_filter('brand'),
model: get_filter('model'),
sort: get_filter('sort'),
date: get_filter('date')
}
)
.done(function (data) {
$('.filter_data').html(data);
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
});
我想要的是当它滚动到页面底部时,它应该加载下一组DB
。
解决方案
我认为你几乎做对了。
要获得无限滚动工作,您需要在第一个脚本的底部添加以下行:
var $window = $( window );
var $document = $( document );
$window.scroll(function () {
// In some cases `$document.height()` is equal to `$window.height()`,
// so you can use the upper condition
//if ( ( window.innerHeight + window.scrollY ) >= document.body.offsetHeight - 300 ) {
if ( $window.scrollTop() >= $document.height() - $window.height() - 300 ) {
console.log('infinite scroll');
flag += 4; // AUTO IN INCREMENT
filter_data();
}
});
这里的小提琴:
为了防止多个请求并在所有数据已加载时停止无限滚动,您可以添加这两个信号量:fetching
和done
// init at the top of your script
var fetching = false;
var done = false;
// add these two lines at the beginning of filter_data
function filter_data() {
// prevent concurrent requests
if(fetching === true) { return; }
fetching = true;
// ...
// condition in the scroll handler should look like this
if (
$window.scrollTop() >= $document.height() - $window.height() - 300 &&
fetching === false && done === false
) {
// ...
// ajax success and error handler
.done( function (data) {
console.log('data received');
// append new data
if(data !== '<h3>No Data Found</h3>') {
//$('.filter_data').html(data); // override
$('.filter_data').append(data); // append
}
// we reached the end, no more data
else {
if(flag === 0) $('.filter_data').append(data); // display initially "no data found"
done = true;
}
flag += 4; // move here. increment only once on success
fetching = false; // allow further requests again
})
.fail( function( error ) {
console.log( 'An error occurred while fetching', error )
// TODO: some error handling
});
这里是完整的小提琴:https ://jsfiddle.net/fus6hyar/
它不起作用的可能原因:
抱歉这个愚蠢的问题,但我不知道你的 html 标记。你是滚动高度>窗口高度吗?
- 这是相同的代码,但内容高度 < 窗口高度。你可以看到在这种情况下滚动事件没有被触发(因为没有什么可以滚动的)。
- https://jsfiddle.net/623wmbut/4/
如果您的滚动处理程序正在工作并且将触发无限滚动。您应该检查您的请求是否正常。向 post 请求添加错误处理程序,检查您的请求是否有问题并添加一些日志。其中一个日志必须出现在控制台中,或者您遇到服务器超时错误或请求未正确发送之类的东西。但是,如果您收到来自服务器的响应(或没有),您将查看您的服务器数据是否正确,以及是否需要调试您的 php/sql 代码或进一步检查您的 javascript。
.done( function (data) {
console.log('data received', data);
// ...
})
.fail( function( error ) {
console.log( 'An error occurred while fetching', error )
// some error handling ...
});
- 如果已接收到数据但仍不会呈现,请检查选择器是否仍然正确/可用:
.done( function (data) {
console.log('data received', data);
console.log($('.filter_data')); // can this element be found?
// ...
})
如果所有这些都不起作用,您可以尝试在 js 脚本的开头添加更多日志,例如console.log($(window))
检查您是否正确初始化了 JQuery。最后,您可以将您的 html 标记添加到您的问题中,也许有错误。
推荐阅读
- python - 根据索引查找列表中大于条件的对数的最佳代码?
- r - NA富包问题的物种富集
- java - Java drawRect() 方法有奇怪/错误的大小
- python - 枕头 - OSError:无法识别图像文件
- regex - 如何在 Google 表格中找到出现的德语变音符号?
- git - 合并拉取请求时,提交出现在本地不存在的 GitHub 上
- java - Java 泛型继承
- python - 单击带有 Selenium 的 WhatsApp 弹出窗口
- javascript - 使用 webpack 动态更改 Ejs 文件中的脚本标签
- javascript - 由于 useState 挂钩,我无法在 Safari 上正确处理状态