代码之家  ›  专栏  ›  技术社区  ›  sanoj lawrence

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

  •  0
  • sanoj lawrence  · 技术社区  · 5 年前

    SQL 当到达底部但尝试使用此代码时,不会从 SQL语言 .

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

    我试着调试 echo $query 我得到了

    SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC LIMIT 4 OFFSET 10
    

    query

    有人能帮我解决这个问题吗?

     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 .

    0 回复  |  直到 5 年前
        1
  •  3
  •   sergej    5 年前

    我想你做得差不多。

    得到 无限滚动 使用时,需要在第一个脚本的底部添加以下行:

    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/

    不起作用的可能原因:

      • 这是相同的代码,但具有内容高度<窗口高度。您可以看到在这种情况下不会触发scroll事件(因为没有要滚动的内容)。
      • https://jsfiddle.net/623wmbut/4/
    .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标记添加到问题中,可能有错误。