我试着用了一些例子,但不知何故,它不起作用。请给我指路。
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
td, th {
padding: 10px;
}
</style>
</head>
<body>
<h2>Convert JSON data into a html table using Javascript</h2>
<p>Click the following button to convert JSON results into HTML table</p><br>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3> Resulting Table: </h3>
<div id="container"></div>
<script>
function convert() {
// Sample JSON data
let jsonData = {
"data":[
{
"customer Name": "ganesh",
"ami":"T6767667",
"state":"closed",
"ssoId":"dhhhdhv",
"convId":"I90098890098",
"account number":"2233233"
},
{
"customer Name": "putta",
"ami":"T6767668",
"state":"closed",
"ssoId":"dhhhdhY",
"convId":"I90098890099",
"account number":"2233234"
}
],
"metadata":{
"": "",
"outcome":{
"status":200,
"code":0,
"type":"OK",
"message":""
}
}
};
let container = document.getElementById("container");
let table = document.createElement("table");
let cols = Object.keys(jsonData[0]);
let thead = document.createElement("thead");
let tr = document.createElement("tr");
cols.forEach((item) => {
let th = document.createElement("th");
th.innerText = item;
tr.appendChild(th);
});
thead.appendChild(tr);
table.append(tr)
jsonData.forEach((item) => {
let tr = document.createElement("tr");
let vals = Object.values(item);
vals.forEach((elem) => {
let td = document.createElement("td");
td.innerText = elem;
tr.appendChild(td);
});
table.appendChild(tr);
});
container.appendChild(table)
}
</script>
</body>
</html>
1条答案
按热度按时间vfhzx4xs1#
您提供的代码似乎几乎是正确的,但有一个小问题。您试图访问j
sonData[0]
,但jsonData不是数组,它是一个具有“data”属性的对象,该属性包含您要遍历的数组。您应该访问jsonData.data以访问array.pls
我使用
jsonData.data
访问数据对象数组,还为表格标题行添加了<thead>
。此外,我在追加表之前清除了容器,以确保在多次单击按钮时表会更新。代码片段