【问题标题】:How to display Google Sheet in HTML format using JSON如何使用 JSON 以 HTML 格式显示 Google Sheet
【发布时间】:2015-12-01 15:57:15
【问题描述】:

我想使用此 Google 表格中的数据以 HTML 格式显示酒店列表: https://docs.google.com/spreadsheets/d/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/

我正在使用 JSON 和 jQuery,并希望使用 jQuery 循环遍历所有行,以 HTML 格式显示它们。

到目前为止,我已经设法使用 JSON 显示一些内容,但我不确定如何继续显示所有行: 代码笔:http://codepen.io/aljohnstone/pen/adobow

$.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
//remove http:// for a text
var url = data.feed.entry[0]['gsx$url']['$t'];
var shortUrl = url.replace('http://', '');
//give id's google sheet values
$('#bandb').text(data.feed.entry[0]['gsx$name']['$t'])
$('#description').text(data.feed.entry[0]['gsx$description']['$t'])
$('#image').attr("src", (data.feed.entry[0]['gsx$image']['$t']));
$('#link').text(shortUrl).attr("href", (data.feed.entry[0]['gsx$url']['$t']));
});

【问题讨论】:

    标签: javascript jquery html json


    【解决方案1】:

    使用jqueryforeach

        $.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
        $.each(data.feed.entry,function(i,v){
    
    var url = v.gsx$url.$t;
        var shortUrl = url.replace('http://', '');
         var data = $('<div class="listing">').append('<img src="'+v.gsx$image.$t+'" id="image"/><h4 id="bandb">'+v.gsx$name.$t+'</h4><p id="description">'+v.gsx$description.$t+'</p><a href="'+v.gsx$url.$t+'" id="link">'+shortUrl+'</a>');
          $('body').append(data);
        });
    
    });
    

    http://codepen.io/anon/pen/mVbypE?editors=001

    【讨论】:

    • 这是一个很好的答案。也许这是 OP 真正想要的,我只是关注一般的迭代问题。
    • 感谢您的回复。这是做我想做的事的好方法!
    【解决方案2】:

    我建议使用前端模板框架,例如mustache.js。这方面有很多选择。您通常在模板框架中所做的是定义一个 HTML 模板,该模板为您的数据使用占位符。然后,在您的 javascript 中,您将数据对象传递到模板中。下面是它在小胡子上的样子:

    模板

    <script id="listing-template" type="text/html">
        <div class="listing">
            <img class="image" src="{{gsx$image.$t}}"/>
            <h4 class="bandb">{{gsx$name.$t}}</h4>
            <a class="link" href="{{gsx$url.$t}}">{{gsx$url.$t}}</a>
            <p class="description">{{gsx$description.$t}}</p>
        </div>
    </script>    
    

    JavaScript

    <script>
    
        $.getJSON('http://cors.io/?u=https://spreadsheets.google.com/feeds/list/1pksFEATRRWfOU27kylZ1WLBJIC-pMVxKk9YlCcDG0Kk/od6/public/values?alt=json',function(data){
            // loop through the entry object and append new templated elements to body element
            $("body").mustache("listing-template",data.feed.entry);
    
        });
    
    </script>
    

    我省略了 mustache 框架的初始化细节,但这是大体思路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多