无限滚动:使用Ajax调用加载更多数据?

时间:2018-02-21 05:26:27

标签: javascript jquery ajax

我正在尝试实现一个无限滚动表,显示用户的姓名,地址和电子邮件。首先,我导入了json-server软件包并在名为users.js的单独文件中创建了一个带有fakerjs的API端点,以便在localhost上提供:

var faker = require('faker')

function generateUsers () {
  var users = [];
  var loading = true;
  for(var i=0;i<50;i++) {
    var name = faker.name.findName()
    var email = faker.internet.email()
    var city = faker.address.city()
    var country = faker.address.country()
    users.push({
      "name": name,
      "email": email,
      "city": city,
      "country": country
    })
  }
  return { "users": users }
}
module.exports = generateUsers

我的问题是“每次滚动到页面末尾时如何加载另一批50个用户?”在初始加载时,它只加载user.js文件中指定的50个用户。我想我可以在ajax成功函数中将更多数据推送到用户数组中,但我不确定如何实现它。

$(document).ready(function(){
    var currentPageNumber = 1;
    loadMore(currentPageNumber);
$(window).scroll(function() {

    if($(window).scrollTop() ==  $(document).height()- $(window).height())
    {

        loadMore(currentPageNumber);
        currentPageNumber +=1;
    }
  });
    function loadMore(currentPage){
        $.ajax({
            method: "GET",
            url: "http://localhost:3000/users?_page="+ currentPage,
            dataType: 'json',
            success: function(data) {
                var  last = data[data.length-1];
                    for(var i=0;i<data.length;i++) {

                       $('tbody').append("<tr><td>"+ data[i].name+"</td><td>"+ 
                       data[i].email+"</td><td>" 
                       + data[i].city + "," + data[i].country+ "</td></tr>")




            },
            error: function(data) {
                    console.log("Something went wrong!");
            }

    })
}

1 个答案:

答案 0 :(得分:0)

你的javascript中有一些拼写错误,请尝试使用下面的代码(我根据我的建议写了一些评论)

var currentPageNumber = 1; // initialization before all functions

$(document).ready(function(){
    loadMore(currentPageNumber);
});

$(window).scroll(function() {
    if( $(window).scrollTop() == $(document).height() - $(window).height() ){
        currentPageNumber++; //increment by one before calling again loadMore()
        loadMore(currentPageNumber);
    }
});

function loadMore(currentPage){

    $.ajax({
        method: "GET",
        url: "http://localhost:3000/users?_page="+ currentPage,
        dataType: 'json',
        cache: false, //avoid browser cache ajax requests
        success: function(data) {

            $.each(data, function(key, val) { // use jQuery.each, easier and clean

                $('tbody').append("<tr><td>"+ val.name+"</td><td>"+ 
                val.email+"</td><td>" 
                + val.city + "," + val.country+ "</td></tr>");

            });

        },
        error: function(data) {
            console.log("Something went wrong!")
        }
    });

}