Pagination: using a “Get More” button with getJSON

2019-04-02 00:52发布

问题:

I am completely new to this, so please forgive me if I don't get enough information. I'm displaying potentially thousands of records using JSON and a listview, however I need to only show 20 at a time, with a "show more" button at the bottom. I'm not understanding how I would change my current javascript to allow for this, hopefully someone can point me in the right direction. I've been trying to apply this code to get it to work, but unsuccessfully:

http://jsfiddle.net/knuTW/2/

My current javascript to display the JSON data:

function getEmployeeList() {
$.getJSON(serviceURL + 'getmeals.php?calfrom='+ var1 + '&calto=' + var2, function(data) {
    $('#employeeList li').remove();
    employees = data.items;
    $.each(employees, function(index, employee) {
        $('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
            '<img src="http://www.restaurants.com/assets/img/logos/' + employee.restaurant + '.jpg"/>' +    
                '<h4>' + employee.meal_item + '</h4>' +
                '<p>Calories: ' + employee.calories + '</p>' +
                '<span class="ui-li-count">' + employee.protein + '</span></a></li>');

    });
    $('#employeeList').listview('refresh');
});
}

HTML:

<div id="employeeListPage" data-role="page" >

<div data-role="header" data-position="fixed">
    <h1>Restaurant Meals</h1>
</div>

<div data-role="content">
     <ul id="employeeList" data-role="listview" data-filter="true"></ul>
     <ul class="load-more"><a href="#">Load More</a></ul>
</div>      

回答1:

The idea is to add two parameters to your $.getJSON : limit and offset.

Limit is the number of rows you want. So let's say 20 rows.

Offset is the row number where you want to start your search. So 0 then 20 then 40 etc.

By clicking "get more", you repeat your $.getJSON with an offset of +20.

In the backend, your SQL query should look like:

$query = "SELECT * FROM table LIMIT $offset, $limit";

When the query returns nothing, it means the user reaches the end.

Then you can hide the "get more" button.


Another solution is to get all the employees with a single $.GetJSON then store the result in an variable. You start by displaying the first 20 employees. If the user clicks on "get more", you display the next 20 employees. When there are no more employees in your array, you hide the "get more" button.

With this solution, you will avoid to make several requests to your server.


You can also look for a plugin to make your pagination.

Some examples:

  • https://github.com/beneverard/jqPagination
  • https://github.com/luis-almeida/jPages
  • https://github.com/gbirke/jquery_pagination
  • https://github.com/fedecarg/jquery-paginate
  • https://github.com/wesnolte/Pajinate