简体   繁体   English

无限滚动与MySQL数据

[英]Infinite Scroll with MySQL Data

I have followed help located in this topic: Using infinite scroll w/ a MySQL Database 我遵循了位于本主题中的帮助: 使用带有MySQL数据库的无限滚动

And have gotten close to getting this working properly. 并且已经接近使其正常工作。 I have a page that is displayed in blocks using jquery masonry, in which the blocks are populated by data from a mysql database. 我有一个页面使用jquery砌体显示在块中,其中的块由mysql数据库中的数据填充。 When I scroll to the end of the page I successfully get the loading.gif image but immediately after the image it says "No more posts to show." 当我滚动到页面的末尾时,我成功获取了loading.gif图像,但图像后立即显示“没有其他帖子可显示”。 which is what it should say if that were true. 如果那是真的,那应该说些什么。 I am only calling in 5 posts initially out of about 10-15, so the rest of the posts should load when I reach the bottom of the page but I get the message that is supposed to come up when there really aren't any more posts. 我最初只在5个帖子中调用了10-15个帖子,所以当我到达页面底部时,其余的帖子应该加载,但是我收到的消息应该是在实际上没有更多的时候出现了帖子。

Here is my javascript: 这是我的JavaScript:

var loading = false;
    $(window).scroll(function(){
        if($(window).scrollTop() == $(document).height() - $(window).height()) {   
            var h = $('.blockContainer').height();
            var st = $(window).scrollTop();
            var trigger = h - 250;

              if((st >= 0.2*h) && (!loading) && (h > 500)){
                loading = true;
                $('div#ajaxLoader').html('<img src="images/loading.gif" name="HireStarts Loading" title="HireStarts Loading" />');
                $('div#ajaxLoader').show();
                $.ajax({
                    url: "blocks.php?lastid=" + $(".masonryBlock:last").attr("id"),
                    success: function(html){
                        if(html){
                            $(".blockContainer").append(html);
                            $('div#ajaxLoader').hide();
                        }else{
                            $('div#ajaxLoader').html('<center><b>No more posts to show.</b></center>');
                        }
                    }
                });
            }
        }
    });

Here is the php on the page the blocks are actually on. 这是块实际位于的页面上的php。 This page initially posts 5 items from the database. 此页面最初从数据库中发布了5个项目。 The javascript grabs the last posted id and sends that via ajax to the blocks.php script, which then uses the last posted id to grab the rest of the items from the database. javascript捕获最后发布的ID,然后通过ajax将其发送到blocks.php脚本,然后脚本使用最后发布的ID从数据库中获取其余项目。

$allPosts = $link->query("/*qc=on*/SELECT * FROM all_posts ORDER BY post_id DESC LIMIT 5");
        while($allRows = mysqli_fetch_assoc($allPosts)) {
            $postID = $link->real_escape_string(intval($allRows['post_id']));
            $isBlog = $link->real_escape_string(intval($allRows['blog']));
            $isJob = $link->real_escape_string(intval($allRows['job']));
            $isVid = $link->real_escape_string(intval($allRows['video']));
            $itemID = $link->real_escape_string(intval($allRows['item_id']));

            if($isBlog === '1') {
                $query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
                $result = $link->query($query);
                while($blogRow = mysqli_fetch_assoc($result)) {
                    $blogID = $link->real_escape_string($blogRow['blog_id']);
                    $blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
                    $blogDate = $blogRow['pub_date'];
                    $blogPhoto = $link->real_escape_string($blogRow['image']);
                    $blogAuthor = $link->real_escape_string($blowRow['author']);
                    $blogContent = $link->real_escape_string($blogRow['content']);  

                    //clean up the text
                    $blogTitle = stripslashes($blogTitle);
                    $blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));           

                    echo "<div class='masonryBlock' id='".$postID."'>";
                    echo "<a href='post.php?id=".$blogID."'>";
                    echo "<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>";
                    echo "<strong>".$blogTitle."</strong>";
                    echo "<p>".$blogContent."</p>";
                    echo "</a>";
                    echo "</div>";

                }
            }

Here is the php from the blocks.php script that the AJAX calls: 这是AJAX调用的blocks.php脚本中的php:

//if there is a query in the URL
if(isset($_GET['lastid'])) {

//get the starting ID from the URL
$startID = $link->real_escape_string(intval($_GET['lastid']));
//make the query, querying 25 fields per run
$result = $link->query("SELECT  * FROM all_posts ORDER BY post_id DESC LIMIT '".$startID."', 25");

$html = '';
//put the table rows into variables
while($allRows = mysqli_fetch_assoc($result)) {
    $postID = $link->real_escape_string(intval($allRows['post_id']));
    $isBlog = $link->real_escape_string(intval($allRows['blog']));
    $isJob = $link->real_escape_string(intval($allRows['job']));
    $isVid = $link->real_escape_string(intval($allRows['video']));
    $itemID = $link->real_escape_string(intval($allRows['item_id']));

    //if the entry is a blog
    if($isBlog === '1') {
        $query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
        $result = $link->query($query);
        while($blogRow = mysqli_fetch_assoc($result)) {
            $blogID = $link->real_escape_string($blogRow['blog_id']);
            $blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
            $blogDate = $blogRow['pub_date'];
            $blogPhoto = $link->real_escape_string($blogRow['image']);
            $blogAuthor = $link->real_escape_string($blowRow['author']);
            $blogContent = $link->real_escape_string($blogRow['content']);  

            $blogTitle = stripslashes($blogTitle);
            $blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));

            $html .="<div class='masonryBlock' id='".$postID."'>
                    <a href='post.php?id=".$blogID."'>
                    <div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>
                    <strong>".$blogTitle."</strong>
                    <p>".$blogContent."</p>
                    </a></div>";

        }
    }
    echo $html;
}

I have tried using the jquery infinite-scroll plugin, but it seemed much more difficult to do it that way. 我已经尝试过使用jquery无限滚动插件,但是用这种方法似乎要困难得多。 I don't know what the issue is here. 我不知道这是什么问题。 I have added alerts and did testing and the javascript script is fully processing, so it must be with blocks.php right? 我添加了警报并进行了测试,并且javascript脚本正在完全处理中,因此它必须与blocks.php对不对?

EDIT: I have made a temporary fix to this issue by changing the sql query to SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15 编辑:通过将sql查询更改为SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15我对此问题进行了临时修复SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15

The blocks are now loading via ajax, however they are only loading one block at a time. 现在,这些块是通过ajax加载的,但是它们一次只能加载一个块。 The ajax is sending a request for every single block and they are fading in one after another, is it possible to make them all fade in at once with jquery masonry? Ajax正在为每个单个块发送一个请求,并且它们正在逐个消失,是否可以通过jquery石工一次使它们全部消失?

I seen your code in another answer, and I would recommend using the LIMIT functionality in MySql instead of offsetting the values. 我在另一个答案中看到了您的代码,建议您在MySql中使用LIMIT功能,而不是偏移值。 Example: 例:

SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".(((int)$page)*5)."',5

This will just take a page number in the AJAX request and get the offset automatically. 这只会在AJAX请求中使用页码,并自动获取偏移量。 It's one consistent query, and works independent of the last results on the page. 这是一个一致的查询,并且独立于页面上的最后结果运行。 Send something like page=1 or page=2 in your jQuery code. 在您的jQuery代码中发送诸如page = 1或page = 2之类的内容。 This can be done a couple different ways. 这可以通过几种不同的方式完成。

First, count the number of elements constructed on the page and divide by the number on the page. 首先,计算页面上构造的元素数量,然后除以页面上的数量。 This will yield a page number. 这将产生页码。

Second, you can use jQuery and bind the current page number to the body: 其次,您可以使用jQuery并将当前页码绑定到正文:

$(body).data('page', 1)

Increment it by one each page load. 每加载一页将其递增1。

Doing this is really the better way to go, because it uses one query for all of the operations, and doesn't require a whole lot of information about the data already on the page. 这样做确实是更好的方法,因为它对所有操作都使用一个查询,并且不需要有关该页面上已有数据的大量信息。

Only thing to note is that this logic requires the first page request to be 0, not 1. This is because 1*5 will evaluate to 5, skipping the first 5 rows. 唯一需要注意的是,此逻辑要求第一页请求为0,而不是1。这是因为1 * 5将求值为5,从而跳过了前5行。 If its 0, it will evaluate to 0*5 and skip the first 0 rows (since 0*5 is 0). 如果其值为0,它将求值为0 * 5,并跳过前0行(因为0 * 5为0)。

Let me know any questions you have! 让我知道您有任何疑问!

Have you tried doing any debugging? 您是否尝试过调试?

If you are not already using, I would recommend getting the firebug plugin. 如果您尚未使用,我建议您获取firebug插件。

Does the ajax call return empty? Ajax调用返回空吗? If it does, try echoing the sql and verify that is the correct statement and that all the variables contain the expected information. 如果是这样,请尝试回显sql并确认该语句正确,并且所有变量都包含预期的信息。 A lot of things could fail considering there's a lot of communication happening between client, server and db. 考虑到客户端,服务器和数据库之间发生大量通信,许多事情可能会失败。

In response to your comment, you are adding the html in this piece of code: 为了回应您的评论,您需要在这段代码中添加html:

if(html){
     $(".blockContainer").append(html);
     $('div#ajaxLoader').hide();
}

I would do a console.log(html) and console.log($(".blockContainer").length) before the if statement. 我会在if语句之前执行console.log(html)console.log($(“。blockContainer”)。length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM