页面滚动问题上的AJAX / JSON动态内容加载

时间:2015-01-29 06:07:01

标签: jquery ajax json scrollbar

目前正在尝试迭代json对象,为对象格式化HTML,然后在用户向下滚动页面时动态加载每个对象,这是我当前的问题,我遍历json对象,在页面滚动时显示它们,但是当我向下滚动它显示所有对象,当我希望它显示每个对象时,当用户向下滚动页面时,显示更多的json对象。

HTML代码

    <body>
     <div id='container'>
     <div id='content'>
     <article class='tumblrPost'>
     <header>
        <h1> Dragonball Z Motivation </h1>
    </header>
         <img src='images/dragonball_z.jpg' alt='dragonball z' title='dbz' />
    <footer>
            <h1> Watch the Video Life & Motivation with Dragonball Z </h1>
    </footer>
    </article>
        </div>
        </div>
        </body>

javascript代码

    $('document').ready(function() {
    var articlePosts = $('div#content article');
    $('div#content').children().first().css('display',  'block').animate({opacity: 1.0}, 1000);
   $(window).on('scroll', function() {
    if($(window).scrollTop() == $('document').height() -   $('window').height()) {
         getPosts();
        }
    });
  }); 
      function getPosts() {
      var visiblePosts = $('div#content article:visible');
      $.getJSON('animeTest.json', function(data) {
      $.each(data, function(key, val) {
        $(window).unbind('scroll');
        var output = $("<article class='tumblrPost'></article>");
        var header = $("<header></header>");
        header.append("<h1>" + val.header + "</h1>").appendTo(output);
        output.append("<img src='images/" + val.image + "' title='Image' />");
        var footer = $("<footer></footer>");
        footer.append("<h1>" + val.footer + "</h1>").appendTo(output);
        visiblePosts.last().after(output);
        if($(window).scrollTop() >= visiblePosts.last().offset().top - 100) {
        output.css('display', 'block').animate({opacity: 1.0}, 1000);
        }
    });     
});

}

2 个答案:

答案 0 :(得分:0)

每次调用getPosts()时;在文章标签中附加一个空元素标签(即帖子的结尾),为该元素添加一个id 当用户滚动页面时 并获取该空元素标记的scrolltop位置,然后再次调用getPosts();并做同样的事情......

答案 1 :(得分:0)

而不是使用$(&#39;文档&#39;)。height()和$(&#39; window&#39;)。height(),使用 $(document).height()和$(window).height()。与JQuery3.6完美配合。

   $(document).ready(function () {
     var limit=10;
     var offset = limit;
     $(window).on('scroll', function() {
        if($(window).scrollTop() == $(document).height() -  $(window).height()) {
           //alert("reached the bottom");
           $.post('ajax_handler.php',
                    {
                        offset: offset,
                        limit : limit,
                    },
                    function (data, status) {
                        if (status=="success"){
                                    $('#tbl_customers').append(data);
                                    offset+=limit;                      
                        }
                    }
                );
        }
    });             
    });
相关问题