将“加载更多”添加到从Google电子表格中通过$.getJSON接收的数据输出中

Add «Load More» to data-output received with $.getJSON from Google Spreadsheet

本文关键字:getJSON 输出 数据 电子表格 Google 加载 加载更多 添加      更新时间:2023-09-26

在使用Google电子表格作为"后端"时,我通过Google的JSON-Output(https://spreadsheets.google.com/feeds/list/MySpreadsheetID/1/public/values?alt=json)和jQuerys $.getJSON(...)获取电子表格的数据,处理数据(将值添加到数组中)并通过循环将数据/内容添加到前端数组。

现在假设Google电子表格有大约200行和大约10列(大量数据)填充了数据。我正在使用这些数据在前端创建信息卡(每行 = 一张卡,200 行 = 200 张卡......这显然对"首次加载"的浏览器进行了相当多的工作。

如何添加"加载更多"例程,以在构建前端时降低浏览器负载/工作?

目标是加载完整的 JSON,但只先将 X 行(= X 卡)的数据添加到前端,并且仅在用户单击"加载更多"元素时才加载接下来的 X 行,然后在第二次单击时加载接下来的 X 行,依此类推,直到所有行/卡都已构建完毕。

我的简化代码(获取所有行并在首次加载时创建所有卡片):

var rowCount,
    row1 = [],
    row2 = [],
    row3 = [],
        $cardsContainer = $('.js-cardsContainer');
function processDataGoogle(data) {
    rowCount = Object.keys(data.feed.entry).length;
    for(var i in data.feed.entry) {
        row1.push("" + data.feed.entry[i].gsx$row1.$t);
        row2.push("" + data.feed.entry[i].gsx$row2.$t);
        row3.push("" + data.feed.entry[i].gsx$row3.$t);
    }
}
function addCards() {
    for(var index = 0; index < rowCount; index++) {
        $cardsContainer.append($('<article class="card"><h1>'+row1[index]+'</h1><p>'+row2[index]+'</p><a href="#">'+row3[index]+'</a></article>'));
    }
}
$(document).ready(function() {
    $.getJSON('https://spreadsheets.google.com/feeds/list/MySpreadsheetID/1/public/values?alt=json', function(data) {
        processDataGoogle(data);
        addCards();
    });
});

我们可以更改addCards(),以便在单击Load More后仅加载项目:

var loadMoreClicks = 1;
function addCards() {
var CARDS_TO_LOAD = 10; // number of cards to load once load more is clicked.
    for(var index = (CARDS_TO_LOAD * (loadMoreClicks - 1 )); index < (CARDS_TO_LOAD * loadMoreClicks); index++) {
        $('.js-cardsContainer').append($('<article class="card"><h1>'+row1[index]+'</h1><p>'+row2[index]+'</p><a href="#">'+row3[index]+'</a></article>'));
    }
}
$("#load-more").click(function(){
        loadMoreClicks += 1;
        addCards();    
});

在 HTML 中:

<button id="load-more">Load More</button>

注意:加载所有物品后需要处理。