无限滚动显示范围之间的东西

时间:2016-02-27 04:42:15

标签: javascript php jquery ajax

当我在范围之间无限滚动时,如何显示某些内容?

例如:我想在3个范围内无限滚动Feed时显示我的广告。

1 TEXT1
2 TEXT2
3 TEXT3

Ads //Added when it's feed by 3 range.

4 TEXT4
5 TEXT5
6 TEXT6

Ads //Added when it's feed by 3 range.

...(Repeat until finish)

scroll.php

<?php
include('db.php');

if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];

 call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
 $page = $data['page'];
 if($page==1){
 $start = 0;
 }
 else{
 $start = ($page-1)*$limit;
 }

 $sql = "select * from infinitescroll order by id asc limit $start,$limit";
 $str='';
 $data = $con->query($sql);
 if($data!=null && $data->num_rows>0){
 while( $row = $data->fetch_array(MYSQLI_ASSOC)){
 $str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p></div>";
 }
 $str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
 }else{
 $str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
 }
echo $str;
}
?>

scroll.js

 var ajax_arry=[];
 var ajax_index =0;
 var sctp = 100;
 $(function(){
 $('#loading').show();
 $.ajax({
 url:"scroll.php",
 type:"POST",
 data:"actionfunction=showData&page=1",
 cache: false,
 success: function(response){
 $('#loading').hide();
 $('#demoajax').html(response);

 }

 });
 $(window).scroll(function(){

 var height = $('#demoajax').height();
 var scroll_top = $(this).scrollTop();
 if(ajax_arry.length>0){
 $('#loading').hide();
 for(var i=0;i<ajax_arry.length;i++){
 ajax_arry[i].abort();
 }
 }
 var page = $('#demoajax').find('.nextpage').val();
 var isload = $('#demoajax').find('.isload').val();

 if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
 $('#loading').show();
 var ajaxreq = $.ajax({
 url:"scroll.php",
 type:"POST",
 data:"actionfunction=showData&page="+page,
 cache: false,
 success: function(response){
 $('#demoajax').find('.nextpage').remove();
 $('#demoajax').find('.isload').remove();
 $('#loading').hide();

 $('#demoajax').append(response);

 }

 });
 ajax_arry[ajax_index++]= ajaxreq;

 }
 return false;

 if($(window).scrollTop() == $(window).height()) {
 alert("bottom!");
 }
 });

});

此处的示例来自原始网站的实时Demo

1 个答案:

答案 0 :(得分:1)

尝试跟踪数据提取的索引

$index = 0; 
while( $row = $data->fetch_array(MYSQLI_ASSOC)){ 
//... your other code 
if($index++%3==2){ 
$str.="ad stuff"; 
} 

}