Federico Cargnelutti

Simple is better than complex. Complex is better than complicated. | @fedecarg

JavaScript: Retrieve and paginate JSON-encoded data

with 5 comments

I’ve created a jQuery plugin that allows you to retrieve a large data set in JSON format from a server script and load the data into a list or table with client side pagination enabled. To use this plugin you need to:

Include jquery.min.js and jquery.paginate.min.js in your document:

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.paginate.min.js"></script>

Include a small css to skin the navigation links:

<style type="text/css">
a.disabled {
    text-decoration: none;
    color: black;
    cursor: default;
}
</style>

Define an ID on the element you want to paginate, for example: “listitems”. If you have a more than 10 child elements and you want to avoid displaying them before the javascript is executed, you can set the element as hidden by default:

<ul id="listitems" style="display:none"></ul>

Place a div in the place you want to display the navigation links:

<div id="listitems-pagination" style="display:none">
    <a id="listitems-previous" href="#" class="disabled">&laquo; Previous</a>
    <a id="listitems-next" href="#">Next &raquo;</a>
</div>

Finally, include an initialization script at the bottom of your page like this:

<script type="text/javascript">
$(document).ready(function() {
    $.getJSON('data.json', function(data) {
        var items = [];
        $.each(data.items, function(i, item) {
            items.push('<li>' + item + '</li>');
        });
        $('#listitems').append(items.join(''));
        $('#listitems').paginate({itemsPerPage: 5});
    });
});
</script>

You can fork the code on GitHub or download it.

About these ads

Written by Federico

October 9, 2011 at 7:43 pm

5 Responses

Subscribe to comments with RSS.

  1. Why all this stuff? Dojo got this already build in ! ;-)

    Sascha-Oliver Prolic

    October 23, 2011 at 7:02 pm

  2. Oh well, next time I’ll use Dojo :)

    Federico

    October 24, 2011 at 8:36 am

  3. Nice plugin
    I remember it, perhaps in the future I will use them

    Oleg Lobach

    November 8, 2011 at 7:43 am

  4. Hi,

    Thanks for your plugin, very useful.

    I noticed that if I have around 300-500 items in list script working very slow.

    Can you please suggest something?

    Yuriy Salmin

    January 28, 2012 at 2:04 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 544 other followers

%d bloggers like this: