使用 AJAX 调用获取动态数据,以便在用户到达底部时加载到“


Using AJAX call to get dynamic data to load in '<div>' when user reaches the bottom

"中。

我正在尝试实现一种功能,当用户到达"div"末尾时,该功能可以从数据库中加载更多数据,类似于Twitter。我有一个名为"userposts_panel"的"div",它由其他几个用于显示数据库中内容的div 组成。即

<div id="userposts_panel">   
    <?php echo "<br/>
            <div class='new_msg'>  
               <div class='user_dp'>
                 <img src='$profile_pic' width= '65px' height= '68px'/>
               </div>
               <div class='msg_content'>
                    <span>$message_content </span> <br/> <br/>
               </div>
               <div class='user_details'> 
                    <span>Posted by: </span> 
                    <a href='$thoughts_by'> <b> $name_of_user </b> </a> on $date_of_msg 
               </div>
            </div><br/>"; ?>
</div>

我定义了以下JavaScript,它获取所有数学数据,例如当用户到达页面末尾时等。但是我无法弄清楚我应该如何从数据库中获取新数据并将其发布在同一页面上(请参阅 if 语句(。目前我有一个查询,它在页面上显示数据库中的 10 个帖子 - LIMIT 1 ,当用户滚动到userposts_panel底部时,我需要它来显示除了已经显示的帖子之外还有 10 个新帖子userposts_panel

 function yHandler (){
    var userposts_panel = document.getElementById('userposts_panel');   
    var contentHeight = userposts_panel.offsetHeight; // get page height
    var yOffset = window.pageYoffset;// get vertical scroll position - find out where user is on scroll.
    var y = yOffset + window.innerHeight;
     if (y >=contentHeight){ // if the user scroll to the very bottom, do this..
         userposts_panel.innerHTML += '<div class="userposts_panel"></div>'
         // AJAX call to get more dynamic data here...
         }
 }
    // event listner
    window.onscroll = yHandler;

我是否必须创建一个新的div 而不是使用userposts_panel来显示新内容,因为它已经存在?如何让它使用 AJAX 从div 中的数据库加载数据?

我试图将答案分成几个部分。

a( 到达页面底部时的处理程序

$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        //Run the ajax call or other here
    }
});

b( 执行 ajax 调用以获取新数据

var url = "http://____";  //API url
var data = "page=2&tar=xx";  //parameters
$.ajax(
    {
        data: data,
        dataType: 'json',
        type: "POST",
        url: url,
        success: function(response) {
           // Handle the new data here
        }
    }
);

c( 将新数据放入页面中

//Here is just an example on placing data via jquery, for your reference
//To make it simple, you may do it on the server side
$.each(response.data,function(key,value){  //run a loop on the response data, it should be in json format
    var clone_grid = $(".new_msg").last().clone();  //Copy the last new msg div
    clone_grid.find('.user_dp').attr('src',value.image);//change the images of the clone div
    clone_grid.find('.msg_content').html(value.message);//change the message of the clone div
    //...
    //...
    $("#userposts_panel").append(clone_grid);//Place it to the end of the #userposts_panel div
}

我希望它能解决你的问题,对不起我的英语不好。