使用JSON数据填充HTML表格

6
我们需要一些指导,[我们才刚开始编程],并且已经查看了很多示例,但是无法将我们的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)函数应用于标题。它完美地显示,看起来和我们想要的一样。
我们已经谷歌了[很多]并尝试了各种加载/填充脚本,并试图让w3schools上的示例工作 - https://www.w3schools.com/js/js_json_html.asp - 不幸的是,我们对此还相当陌生。
我们的JSON文件/assets/sample.JSON格式正确且符合要求。
如何简单导入JSON以填充id="gable"的表格?

所以,你想从外部文件加载JSON,而不是像上面的代码一样内联使用它? - RyDog
是的 - 我们想要移除内联数据并使用我们的JSON文件/assets/sample.JSON,该文件格式正确且符合要求。我们如何简单地导入JSON以填充表格id="gable"? - BorisNZ
2个回答

20

好的,那么在这个方案中,我将假设您的外部json文件名为'example.json'

您的外部文件应该看起来像这样 example.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代码没有改变,所有的更改都在脚本标签中进行。我将功能拆分为两个新函数。第一个函数(get_json_data)从外部JSON文件获取JSON数据。第二个函数(append_json)将数据追加到表格中。

我在代码中加入了注释以解释每个部分的功能。如果您有任何问题或不清楚的地方,请告诉我。

这是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>

1
谢谢!@RyDog - 100% 完美的解决方案!它完全按照要求运行得很好。非常感谢您的时间和努力,特别是注释!我们正在将更多的 JSON 导入到表格中,所以我们将使用这个作为模板!再次感谢! - BorisNZ

5
您可以编写一个独立于数据字段的函数来创建表格:
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接