2017-09-02 79 views
1

我想使用Ajax php和jquery无限滚动我的页面。 我已经粘贴了jQuery代码doe引用。我试图按顺序使用jquery和php进行发布。我的jQuery代码发送计数到php脚本。 PHP脚本然后根据它收到的数字返回结果。我试图按顺序排列帖子,以免它们重复。当用户到达页面底部时,我会看到帖子。无限滚动:使用Ajax和php排序帖子

任何其他答案,这也是受欢迎的。但我只想使用jquery意义的核心,而不包含任何外部库。

var counta = 0; 
$(document).ready(function(){ 


    $(window).scroll(function() { 

    if($(window).scrollTop() + $(window).height() > $(document).height() - 2000) {    
    // console.log("Here"); 

    $.ajax({    
          type: 'post', 
          url: 'extendost.php',    
          data: '&articles='+counta,    
          success: function (data) {         
          alert(counta); 
          $("#morepost").append(data);              
          counta++; 
          }, 
          error: function (data) {        
          alert(data);         
          }, 
      }); 

    } 
}); 

回答

1

这是我会做什么:

<div id="start">0</div> 
<div class="post_content"></div> 

$(window).data('ajaxready', true).scroll(function(e) { 
    var postHeight = $('#post_content').height(); 
    if ($(window).data('ajaxready') == false) return; 
     var start = parseInt($('#start').text()); 
     var limit = 30; // return 30 posts each 
     if ($(window).scrollTop() >= postHeight - $(window).height() - 400) { 
      var height = $(window).scrollTop(); 
      $(window).data('ajaxready', false); 
      if (start > 0) { 
       var new_start = start + limit; 
       var dataString = {articles : start, limit : limit}; 
       $.ajax({ 
        cache: false, 
        url: 'extendost.php', 
        type: 'POST', 
        data: dataString, 
        success: function(data) { 
         if ($.trim(data).indexOf('NO POST') > -1) { 
          /* stop infinite scroll when no more data */ 
          $('#start').text(0); 
         } else { 
          $('#post_content').append(data); 
          $('#start').text(new_start); 
         } 
         $(window).data('ajaxready', true); 
        } 
       }); 
      } 
     } 
    }); 

这种方式,因为它在$开始滚动,并准备下一次滚动值

然后你的基础值#开始会改变(偏移)和$限制,使您的查询如

$query = "SELECT * FROM articles LIMIT {$limit} OFFSET {$start}"; 
if (!$result = mysqli_query($con, $query) { 
    echo 'NO POST'; 
} else { 
    // fetch and echo your result; 
} 
+0

我编辑了你的答案。它需要.html代替.val,因为我们需要获取div标签之间的html而不是它们的值。 –

+0

是的,我已经更新了我的答案。我将它改为.text()而不是.val()。否则,必须将#start改为输入type =“hidden”。谢谢 –

+0

太棒了!它为我工作。 –