使用JSON数据填充HTML表

Bor*_*sNZ 0 html import json html-table populate

我们会获得一些指导表示感谢,[我们早早进入编码]和已经看过很多例子,但能不能让我们的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>
Run Code Online (Sandbox Code Playgroud)

还有更多的数据行,该表具有CSS样式并将sortTable(n)函数应用于Headers.它显示完美,外观和功能,我们想要的,

我们用Google搜索了[批量]并尝试了各种加载/填充脚本,并尝试在w3schools上运行示例 - https://www.w3schools.com/js/js_json_html.asp - 唉,我们对此很新.

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

我们如何简单地导入JSON来填充表id ="gable"?

RyD*_*Dog 10

好的,所以在这个解决方案中,我将假设您的外部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":" " }
]
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


sor*_*orh 6

您可以使用一个函数来创建独立于数据字段的表:

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;
}
Run Code Online (Sandbox Code Playgroud)