使用PHP和jQuery的无限滚动分页只返回很少的帖子,并使用gif加载程序停止

使用PHP和jQuery的无限滚动分页只返回很少的帖子,并使用gif加载程序停止,php,jquery,infinite-scroll,Php,Jquery,Infinite Scroll,我正在尝试使用PHP和JQuery复制在线找到的无限滚动的代码 但不幸的是,代码中有一个缺陷,使得它只能返回7篇文章,并在向下滚动时停止获取其他文章,在底部留下一个加载gif 一般来说,我不会问这个问题,但代码似乎 相当不错(用外行的话说),我想这会很有帮助 对于社区里像我这样的新手 同时,我将搜索其他资源并尝试自己回答 我的代码如下: Index.php <div class="post-wall"> <div id="post-

我正在尝试使用PHP和JQuery复制在线找到的无限滚动的代码

但不幸的是,代码中有一个缺陷,使得它只能返回7篇文章,并在向下滚动时停止获取其他文章,在底部留下一个加载gif

一般来说,我不会问这个问题,但代码似乎 相当不错(用外行的话说),我想这会很有帮助 对于社区里像我这样的新手

同时,我将搜索其他资源并尝试自己回答

我的代码如下:

Index.php

<div class="post-wall">
        <div id="post-list">
            <?php
            require_once ('db.php');
            $sqlQuery = "SELECT * FROM tbl_posts";
            $result = mysqli_query($conn, $sqlQuery);
            $total_count = mysqli_num_rows($result);
            
            $sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT 7";
            $result = mysqli_query($conn, $sqlQuery);
            ?>
            <input type="hidden" name="total_count" id="total_count"
            value="<?php echo $total_count; ?>" />

            <?php
            while ($row = mysqli_fetch_assoc($result)) {
                $content = substr($row['content'], 0, 100);
                ?>
                <div class="post-item" id="<?php echo $row['id']; ?>">
                    <p class="post-title"><?php echo $row['title']; ?></p>
                    <p><?php echo $content; ?></p>
                </div>
                <?php
                }
                ?>
            </div>
            <div class="ajax-loader text-center">
                <img src="LoaderIcon.gif"> Loading more posts...
            </div>
    </div>

<script type="text/javascript">
$(document).ready(function(){
        windowOnScroll();
});
function windowOnScroll() {
       $(window).on("scroll", function(e){
        if ($(window).scrollTop() == $(document).height() - $(window).height()){
            if($(".post-item").length < $("#total_count").val()) {
                var lastId = $(".post-item:last").attr("id");
                getMoreData(lastId);
            }
        }
    });
}

function getMoreData(lastId) {
       $(window).off("scroll");
    $.ajax({
        url: 'getMoreData.php?lastId=' + lastId,
        type: "get",
        beforeSend: function ()
        {
            $('.ajax-loader').show();
        },
        success: function (data) {
               setTimeout(function() {
                $('.ajax-loader').hide();
            $("#post-list").append(data);
            windowOnScroll();
               }, 1000);
        }
   });
}
</script>
<?php
require_once('db.php');

$lastId = $_GET['lastId'];
$sqlQuery = "SELECT * FROM tbl_posts WHERE id < '" .$lastId . "' ORDER BY id DESC LIMIT 7";

$result = mysqli_query($conn, $sqlQuery);


while ($row = mysqli_fetch_assoc($result))
 {
    $content = substr($row['content'],0,100);
    ?>
    <div class="post-item" id="<?php echo $row['id']; ?>">
        <p class="post-title">  <?php echo $row['title']; ?></p>
        <p><?php echo $content; ?></p>
    </div>
    <?php
}
?>


我会使用类和控制器等进行不同的设置,但作为简单的脚本,我可能会设置如下:

使用以下内容创建名为
getData.php
的文件:

<?php

require_once('db.php');

if (! function_exists('getData')) {
    /**
     * @param int $offset
     * @param int $limit
     * @return array|null
     */
    function getData($offset, $limit, $conn) {
         $offset = (int)$offset;
         $limit  = (int)$limit;
         $sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset";
         $result = mysqli_query($conn, $sqlQuery);
         $rows = [];
         while ($row = mysqli_fetch_assoc($result)) {
             $rows[]= $row;
         }
         return $rows;
     }
}
<?php
require_once ('getData.php');

$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
    'rows' => $rows,
    'offset' => $offset,
];


$data = json_encode($data);

// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
    echo $data;
    exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <style type="text/css">
        body {
            font-family: Arial;
            background: #e9ebee;
            font-size: 0.9em;
        }

        .post-wall {
            background: #FFF;
            border: #e0dfdf 1px solid;
            padding: 20px;
            border-radius: 5px;
            margin: 0 auto;
            width: 500px;
        }

        .post-item {
            padding: 10px;
            border: #f3f3f3 1px solid;
            border-radius: 5px;
            margin-bottom: 30px;
        }

        .post-title {
            color: #4faae6;
        }

        .ajax-loader {
            display: block;
            text-align: center;
        }
        .ajax-loader img {
            width: 50px;
            vertical-align: middle;
        }
    </style>
</head>
<body>
<div class="post-wall">
    <div id="post-list">
        <input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
        <input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
    </div>
    <div class="ajax-loader text-center">
        <img src="LoaderIcon.gif"> Loading more posts...
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function(){
// load the initial rows on page load
        let initialData = <?= $data ?? '' ?>;
        if (initialData) {
            if (initialData.rows) {
                addrows(initialData.rows);
                $('.ajax-loader').hide();
            }
        }
        windowOnScroll();

    });
    function windowOnScroll() {
        $(window).on("scroll", function(e){
            if ($(window).scrollTop() == $(document).height() - $(window).height()){
                console.log('test');
                if($(".post-item").length < $("#total_count").val()) {
                    let offset = $('#offset').val();
                    getMoreData(offset)
                }
            }
        });
    }

    function getMoreData(offset) {
        $('.ajax-loader').show();
        $(window).off("scroll");
        let pageUrl = window.location.href.split('?')[0];
        $.ajax({
            url: pageUrl + '?dataOnly=1&offset=' + offset,
            type: "get",
            success: function (response) {
                response = JSON.parse(response);
                if (response.rows) {
                    addrows(response.rows);
                    if (response.offset) {
                        $('#offset').val(response.offset);
                    }
                    $('.ajax-loader').hide();
                }
                windowOnScroll();
            }
        });
    }

    function addrows(rows) {
        let postList = $("#post-list");
        $.each(rows, function (i, row) {
            let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
            postList.append(rowHtml);
        });
    }
</script>
</body>
</html>
现在,我不能在本地测试,所以可能有一两个错误,但这应该给你一个大致的想法

有一件事我不能100%确定,那就是
if($(窗口).scrollTop()==$(文档).height()-$(窗口).height()){
条件

XSS警告
您没有显示这些“帖子”是如何添加到数据库的,它们可能来自用户以其他形式提交的。如果是这种情况,请确保您了解

此代码极易受影响。您应该使用。您可以添加
控制台.log('test')吗;
在您的
getMoreData
方法的顶部,使用控制台打开的页面检查日志?该消息打印了多少次?是很多次?还是只有几次?@HarryK As@Wesley上面提到的put
console.log('test'));
在您的
getMoreData
顶部,查看是否在控制台中收到消息。此外,在网络选项卡中,您应该看到ajax调用并查看其请求和响应正文。您在控制台中看到多少次“test”打印?“在getMoreData函数上方”可能是错误的位置,请将其添加到getMoreData方法的顶部但在函数内部。我们的想法是查看该方法被调用了多少次。你有一个小疑问。有什么问题吗?你能访问一下吗。。