使用 javascript 从 jsondata.json 文件填充 html 表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19588083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate html table from a jsondata.json file using javascript
提问by Linkz
I am new to javascript and jQuery. I have loaded a JsonData.json
file. I need help to loop through all the data and display it in a HTML table when the user clicks a button.
我是 javascript 和 jQuery 的新手。我已经加载了一个JsonData.json
文件。我需要帮助来遍历所有数据并在用户单击按钮时将其显示在 HTML 表中。
<script>
var a = {};
$.getJSON('JsonData.json', function (data) {
a = data;
});
</script>
My table structure is below:
我的表结构如下:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>IDNumber</th>
</tr>
</table>
My "JsonData.json" file structure is below:
我的“JsonData.json”文件结构如下:
[
{
"ID": 1,
"Name": "John Smith",
"IDNumber": "7606015012088"
},
{
"ID": 2,
"Name": "Molly Malone",
"IDNumber": "8606125033087"
},
{
"ID": 3,
"Name": "Rianna Chetty",
"IDNumber": "6207145122087"
},
{
"ID": 4,
"Name": "Gregory Nazul",
"IDNumber": "8112125042088"
},
{
"ID": 5,
"Name": "Mary Billat",
"IDNumber": "9103317012087"
},
{
"ID": 6,
"Name": "Harry Popadopalous",
"IDNumber": "7206085031088"
},
{
"ID": 7,
"Name": "Jim Beam",
"IDNumber": "5101236012088"
}
]
回答by André Leal
You can use something like:
你可以使用类似的东西:
<script>
var a = {};
$.getJSON('JsonData.json', function (data) {
a = data;
$.each(a, function(idx, elem){
$('table#tbl TBODY').append('<tr><td>'+elem.ID+'</td><td>'+elem.Name +'</td><td>'+elem.IDNumber +'</td></tr>');
});
});
</script>
<table id="tbl">
<thead><tr><th>ID</th><th>Name</th><th>IDNumber</th></tr></thead>
<tbody></tbody>
</table>