Php 在AJAX中到达底部时无法加载更多数据

Php 在AJAX中到达底部时无法加载更多数据,php,ajax,Php,Ajax,当到达底部时,我试图为SQL加载更多数据,但是当我尝试使用此代码时,没有从SQL加载数据 如何将无限滚动添加到此代码 我试图通过echo$query进行调试,结果 SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC LIMIT 4 OFFSET 10 我得到了正确的查询,我还检查了控制台错误,但什么也没有得到,没有从SQL加载数据 有人能帮我解决这个问题吗 var flag = 0;

当到达底部时,我试图为
SQL
加载更多数据,但是当我尝试使用此代码时,没有从
SQL
加载数据

如何将无限滚动添加到此代码

我试图通过
echo
$query
进行调试,结果

SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC LIMIT 4 OFFSET 10
我得到了正确的
查询
,我还检查了控制台错误,但什么也没有得到,没有从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;
}

我想要的是,当它滚动到页面底部时,它应该从
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:
  • 条件2:
若要防止多个请求并停止无限滚动,如果所有数据都已加载,则可以添加以下两个信号量:
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
});
  • 如果已收到数据但仍无法呈现,请检查选择器是否仍然正确/可用:

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

    看看这个问题:@Richard,但当我到达底部时,我的
    偏移量
    值会发生更改。
    allpostdata
    中有多少行?如果表中的行少于10行,则第一个查询将不返回任何行。如果
    flag+=4偏移量怎么可能是10?@DinoCoderSaurus我有17行(现在测试将在将来添加)<代码>标志+=4那么问题是什么solution@DinoCoderSaurus有什么解决方案吗?让我们来吧。谢谢你,在上次更新后做了一些修改,它成功了。
    
    // 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
    });
    
    .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?
        // ...
    })