在 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'] . '&nbsp;/&nbsp;' . $row['mdl'] . '</h6>
<p class="card-text"><strong class="card-text text-dark text-truncate">&#x20B9;&nbsp;' . $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();
}
});

这里是小提琴:

  • 条件 1:https://jsfiddle.net/ra6Lmy54/3/
  • 条件 2:https://jsfiddle.net/8d7qtmy1/

若要防止多个请求并在已加载所有数据时停止无限滚动,可以添加以下两个信号量:fetchingdone

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

它不起作用的可能原因:

  1. 很抱歉这个愚蠢的问题,但我不知道你的 html 标记。您的滚动高度>窗口高度吗?

    • 这是相同的代码,但具有内容高度<窗口高度。您可以看到在这种情况下不会触发滚动事件(因为没有要滚动的内容(。>
    • https://jsfiddle.net/623wmbut/4/
  2. 如果您的滚动处理程序正在工作,则将触发无限滚动。您应该检查您的请求是否正常。向 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 ...
});
  1. 如果已收到数据但仍然不会呈现,请检查选择器是否仍然正确/可用:
.done( function (data) {
console.log('data received', data);
console.log($('.filter_data')); // can this element be found?
// ...
})

如果所有这些操作都不起作用,您可以尝试在 js 脚本的开头添加更多日志,例如console.log($(window))以检查是否正确初始化了 JQuery。最后,您可以将html标记添加到您的问题中,也许有错误。

最新更新