javascript 如何解析这样的 Json 列表并以 HTML 显示其元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18393860/
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
How to parse a Json list like this and display its elements in HTML?
提问by Jane
I got an Json object by using jQuery's getjson() method like that:
我通过使用 jQuery 的 getjson() 方法得到了一个 Json 对象,如下所示:
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON(the_api_url, {}, function(data) {
// do something
});
});
});
});
</script>
The data is an array list, and its format is like this:
数据是一个数组列表,格式如下:
[
{
id : "001",
name : "apple",
class : "fruit",
colour : "red"
},
{
id : "002",
name : "melon",
class : "fruit",
colour : "green"
},
{
id : "003",
name : "banana",
class : "fruit",
colour : "yellow"
}
]
I am new to JavaScript and don't know how to parse and display it in html page. Could you guys help me with the code in the '//do something' part?
我是 JavaScript 新手,不知道如何在 html 页面中解析和显示它。你们能帮我处理“//做某事”部分的代码吗?
回答by Arun P Johny
Add a html element like
添加一个 html 元素,如
<ul id="ct"></ul>
then
然后
$(document).ready(function(){
$("button").click(function(){
$.getJSON(the_api_url, {}, function(data) {
var $ul = $('#ul')
$.each(data, function(idx, item){
$ul.append('<li style="color: ' + item.color + '">' + item.name + '-' + item['class'] +'</li>')
})
});
});
});
回答by Nikhil VJ
This generic function (vanilla Javascript, no external libraries) handles all json arrays; does not need you to configure the columns:
这个通用函数(vanilla Javascript,没有外部库)处理所有 json 数组;不需要您配置列:
function makeTable(D){
var a = '';
cols = Object.keys(D[0]);
a += '<table><thead><tr>';
for(j=0;j<cols.length;j++) {
a+= `<th>${cols[j]}</th>`;
}
a += '</tr></thead><tbody>';
for(i=0;i<D.length; i++) {
a += '<tr>';
for(j=0;j<cols.length;j++) {
a += `<td>${D[i][cols[j]]}</td>`;
}
a += '</tr>';
}
a += '</tbody></table>';
return a;
}
Given your sample data,
鉴于您的样本数据,
D = [
{
id : "001",
name : "apple",
class : "fruit",
colour : "red"
},
{
id : "002",
name : "melon",
class : "fruit",
colour : "green"
},
{
id : "003",
name : "banana",
class : "fruit",
colour : "yellow"
}
];
Here is the output of makeTable(D)
:
这是输出makeTable(D)
:
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>class</th>
<th>colour</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>apple</td>
<td>fruit</td>
<td>red</td>
</tr>
<tr>
<td>002</td>
<td>melon</td>
<td>fruit</td>
<td>green</td>
</tr>
<tr>
<td>003</td>
<td>banana</td>
<td>fruit</td>
<td>yellow</td>
</tr>
</tbody>
</table>
You can use this site to preview HTML: https://www.onlinehtmleditor.net/The original output is all in one line; I used an html formatterto format it.
你可以使用这个站点来预览HTML:https: //www.onlinehtmleditor.net/原始输出是一行;我使用了html 格式化程序来格式化它。