【问题标题】:Populate HTML table with JSON data使用 JSON 数据填充 HTML 表
【发布时间】:2018-12-18 22:03:51
【问题描述】:

我们将不胜感激,[我们还处于编码阶段] 并查看了很多示例,但无法将我们的 JSON 导入表中。

此时我们有表格数据,但是现在可以使用格式正确的 JSON 文件并自动更新,我们希望在加载页面时将其动态加载到表格中。

这是当前使用的示例:

<div>
<p> *** OTHER STUFF HERE ***<p/>
    <table id="gable">
        <colgroup>
            <col class="twenty" />
            <col class="fourty" />
            <col class="thirtyfive" />
            <col class="twentyfive" />
        </colgroup>
        <tr>
            <th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
            <th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
            <th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
            <th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
        </tr>
    </table>
</div>
<script>
var data = [
    { "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
    { "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
    { "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
    { "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
    { "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
    var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
        '<td>' + object.LoC + '</td>' +
        '<td>' + object.BALANCE + '</td>' +
        '<td>' + object.DATE + '</td>';
    table.appendChild(tr);
});
</script>

有更多的数据行,表格具有 CSS 样式并将 sortTable(n) 函数应用于标题。它显示完美,外观和功能都符合我们的要求,

我们已经用谷歌搜索了 [lots] 并尝试了各种加载/填充脚本,并试图让 w3schools 上的示例正常工作 - https://www.w3schools.com/js/js_json_html.asp - 唉,我们对此还很陌生。

我们的 JSON 文件 /assets/sample.JSON 格式正确且符合要求。

我们如何做一个简单的 JSON 导入来填充表 id="gable"?

【问题讨论】:

  • 所以不要像上面的代码那样使用 json 内联,而是要从外部文件加载它?
  • 是 - 100%,我们想要删除内联数据并使用格式正确且符合要求的 JSON 文件 /assets/sample.JSON。我们如何做一个简单的 JSON 导入来填充表 id="gable"?

标签: html json import html-table populate


【解决方案1】:

好的,所以在这个解决方案中,我将假设您的外部 json 文件名为“example.json”

您的外部文件应如下所示 示例.json:

[
  { "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
  { "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
  { "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
  { "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
  { "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]

html 保持不变,所有更改都已在脚本标签中进行。我将功能拆分为 2 个新功能。第一个函数 (get_json_data) 从外部 json 文件中获取 json 数据。第二个函数(append_json)将数据追加到表中。

我在整个代码中都放置了 cmets 来解释一切在做什么。如果您有任何问题或不清楚的地方,请告诉我。

这里是html文件的代码:

<div>
        <p> *** OTHER STUFF HERE ***<p/>
        <table id="gable">
            <colgroup>
                <col class="twenty" />
                <col class="fourty" />
                <col class="thirtyfive" />
                <col class="twentyfive" />
            </colgroup>
            <tr>
                <th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
                <th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
                <th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
                <th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
            </tr>
        </table>
    </div>
    <script>
        //first add an event listener for page load
        document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load

        //this function is in the event listener and will execute on page load
        function get_json_data(){
            // Relative URL of external json file
            var json_url = 'example.json';

            //Build the XMLHttpRequest (aka AJAX Request)
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() { 
                if (this.readyState == 4 && this.status == 200) {//when a good response is given do this

                    var data = JSON.parse(this.responseText); // convert the response to a json object
                    append_json(data);// pass the json object to the append_json function
                }
            }
            //set the request destination and type
            xmlhttp.open("POST", json_url, true);
            //set required headers for the request
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // send the request
            xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
        }

        //this function appends the json data to the table 'gable'
        function append_json(data){
            var table = document.getElementById('gable');
            data.forEach(function(object) {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
                '<td>' + object.LoC + '</td>' +
                '<td>' + object.BALANCE + '</td>' +
                '<td>' + object.DATE + '</td>';
                table.appendChild(tr);
            });
        }
    </script>

【讨论】:

  • 谢谢! @RyDog - 100% 完美的解决方案!根据需要工作得很好。非常感谢您在协助方面的时间和精力 - 特别是 cmets!我们正在将更多的 JSON 导入表中,因此我们将使用它作为模板!再次感谢您!
【解决方案2】:

你可以有一个函数来创建独立于你的数据字段的表:

function updateTable(tableId, jsonData){

  var tableHTML = "<tr>";
  for (var headers in jsonData[0]) {
    tableHTML += "<th>" + headers + "</th>";
  }
  tableHTML += "</tr>";

  for (var eachItem in jsonData) {
    tableHTML += "<tr>";
    var dataObj = jsonData[eachItem];
    for (var eachValue in dataObj){
      tableHTML += "<td>" + dataObj[eachValue] + "</td>";
    }
    tableHTML += "</tr>";
  }

  document.getElementById(tableId).innerHTML = tableHTML;
}

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2018-10-24
    • 2014-07-19
    相关资源
    最近更新 更多