如何使用按钮加载更多JSON项?

时间:2018-02-28 18:35:14

标签: javascript php jquery json

目前,我点击加载按钮时会触发.getJSON。我想要在每次后续点击时加载JSON文件中的下10个项目。目前,每次都会追加前10个项目,而不是数组中的下一个项目。

编辑:我希望所有这些都发生在同一页面上。

JS:

var current = 0; 
$(document).ready(function() {
  $("#get-data").click(function(){ //load JSON data...
  current += 9;
    $.getJSON("api.php", //gets a JSON data from api.php
    function(data,status){     //callback function if request succeeds
        $.each(data.records, function(i,record){//The each() method specifies a function to run for each matched element. Essentially, a loop!
            $("<img/>").attr({"src": record.image, "class": "album", "alt": record.artist}).appendTo(".ajax-loader"); //appends data from json file to the element with id of "images"
            if ( i == 9 ) {
              return false;
            }
        });
        data = data.records.slice(current);
        console.log(data);    
     }); //end of callback function and end of .getJSON statement
   });
});
console.log(current);

JSON:

{"records":[
 {"artist":"At The Drive In","title":"Acrobatic Tenement ","year":"1996","image":"./img/atdi01.jpg","description":"Arguably the the pioneering album of post-hardcore, Acrobatic Tenement is At The Drive In's seminal album. ","ID":"1"},
 {"artist":"At The Drive In","title":"Vaya EP","year":"1999","image":"./img/atdi02.jpg","description":"A near-perfect entry in ATDI's discography, short enough to keep listener's interested and eventually rounded out what would become their pivotal and final album \"Relationship of Command\"","ID":"2"}
...]

1 个答案:

答案 0 :(得分:0)

api.php并不知道您要加载其他数据。你必须将一些参数转发给api.php。 例如:

$.getJSON("api.php?page"+page, //gets a JSON data from api.php with next index
function(data,status) {     //callback function if request succeeds