简体   繁体   中英

Why doesn't the 'infinite scroll' stop loading content?

I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.

I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.

JavaScript

function loadPosts(){
    var target = document.getElementById('PostsContainer');
    var contentHeight = target.offsetHeight;
    var yOffset = window.pageYOffset;
    var y = yOffset + window.innerHeight;
    if(y >= contentHeight){
        var xhr = ajaxObj("POST", "loadContent.php");
        xhr.onload = function(){
            target.innerHTML += xhr.responseText;
        }
        xhr.send("action=loadMore");
    }
}
window.onscroll = loadPosts;

PHP

$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page

$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content

while($current < $totalPosts){
  $sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
  LIMIT $current, $max";
  $result = $db_link->query($sql);
  $posts_list += ... //Collect the data from DB
  $current++;
}
echo $posts_list;

No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.

So in this case what you can do, just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function

so basically Algorithm be like,

...php

while($current < $totalPosts){
......................
......................

  if($current >= $totalPosts)
  {
     $getNext = False;
  }
  else
  {
   $getNext = True;
  }
}

...javasrcipt

function loadPosts(){

   if(!getNext)
     return false;
   else
   {
   ......................
   ......................
   }
}
window.onscroll = loadPosts;

Hope this strategy will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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