简体   繁体   中英

How to limit number of data retrieved from Json (client side)?

I am retrieving data from a Json object with 55 entries, but I would like to limit it to 10 items. What is the best practice for this?

Also what if I later want to click on a button and load more data (let says either 10 or 25 more items)?

My code:

$.ajax({
url: 'data.json',
type: 'GET',
dataType: 'json',
success: function(response) {
    console.log('success!');
    var fixtureHTML = '';

    $.each(response.data, function(key, value) {   
        // do something with data retrieved from JSON


    });

    // Append generated HTML to DOM
    $('.js-load').append(fixtureHTML);

}, // End of Success
error: function() {
    console.log('errror');
}

});

Here is a simple demo. I declare two variables (pagerSize, pageLast) which keep the pager size and the current page index. Then each time the button is clicked I fetch the next data, push them to an array and append them to the document. I have set the pager to just two elements here, you can easily embed this in your code.

 var emp = { "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"}, {"firstName":"John", "lastName":"Peterson"}, {"firstName":"Tomas", "lastName":"Smithson"}, {"firstName":"Peter", "lastName":"Jonathan"}, {"firstName":"Jim", "lastName":"Doveson"}, {"firstName":"Kate", "lastName":"Smith"}, {"firstName":"John", "lastName":"Jones"}, {"firstName":"Nick", "lastName":"Doe"}, {"firstName":"Tim", "lastName":"Smith"}, {"firstName":"Tom", "lastName":"Jones"} ] } var pagerSize = 2; var pageLast = 0; load(emp.employees, pageLast, pagerSize); $('#loader').click(function(){ load(emp.employees, pageLast, pagerSize); }); function load(data,start,limit){ var employees = []; for(var i = start; i < start+limit; i++) { var object = data[i]; var newElement = $('<p/>').attr("id", "emp"+i).text(object.firstName+' '+object.lastName) employees.push(newElement); } $('.js-load').append(employees); $('.js-load').append("<hr>"); pageLast+=limit; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" id="loader" value = "load more"/> <hr> <div class="js-load"></div> 

I'd slice the response object befor parsing.

It's cleaner and you keep the limiting logic outside the workflow.

...
    var limit = 10;
    var data = response.data.slice(0, limit);

    $.each(data, function(key, value) {   
        // do something with data retrieved from JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM