如何从JSON文件中挑选特定元素并将其显示在HTML表格中?在jquery
我想调用一个JSON文件并提取元素并将它们放在HTML表格中。目前,我已经成功地做到这一点通过使来电并在JSON文件中的内容,然后数组通过数组循环和将它们放置在我所动态创建一个HTML表格。我希望能够选择JSON文件中的特定元素,而不是在表格中显示所有元素。如何从JSON文件中挑选特定元素并将其显示在HTML表格中?在jquery
我希望这是有道理的,这里是我的代码:
$.getJSON("my url", function (data) {
var jsonData = [];
$.each(data, function (index, value) {
jsonData.push(value);
});
// Header for table
var tblColumn = [];
for (var i = 0; i < jsonData.length; i++) {
for (var key in jsonData[i]) {
if (tblColumn.indexOf(key) === -1) {
tblColumn.push(key);
}
}
}
//Dynamic Table
var table = document.createElement("table");
//create table row
var tr = table.insertRow(-1);
for (var i = 0; j < tblColumn.length; j++) {
var tblCell = tr.insertCell(-1);
tblCell.innerHTML = tblColumn[i];
tr.appendChild(th);
}
for (var i = 0; i < jsonData.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < tblColumn.length; j++) {
var tblCell = tr.insertCell(-1);
tblCell.innerHTML = jsonData[i][tblColumn[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
这是我的HTML代码:
UPDATE:样品JSON文件:
[
{
"Id": 0,
"ProcessingDate": "2017-08-01T13:08:00.967Z",
"Filename": "string",
"BatchDescription": "string",
"Status": "string",
"UploadedById": 0,
"UploadedByName": "string",
"AuthorisedById": 0,
"AuthorsiedByName": "string",
"UploadedDate": "2017-08-01T13:08:00.967Z",
"ConfirmedDate": "2017-08-01T13:08:00.967Z",
"AuthorisedDate": "2017-08-01T13:08:00.967Z"
}
]
真的会感谢帮助,谢谢。
我看过你的代码并理解你在做什么,但是当我做这类事情我通常建表,这样我可以风格它,当添加一条消息,如“加载数据”它的加载,则当数据准备好了它被添加了。这使得它对用户来说更好一些,而不是出现在没有任何地方的表格上)
我以某种方式创建了这个示例,以便您可以轻松地将新列添加到您的表中只需要添加到fields
阵列和列添加到表头。
<!-- Button to request data -->
<button id="reqBtn">Request Data</button>
<table>
<thead>
<tr>
<!--
Add a column header for each field
you want to display In this example
it will display the ID, Filename,
Status and UploadedDate
-->
<th>ID</th>
<th>Filename</th>
<th>Status</th>
<th>Upload Date</th>
</tr>
</thead>
<tbody id="rows"></tbody>
</table>
<script type="text/javascript">
/*
In order you want them to display add
the field name into this array
In this example it will display the
ID, Filename, Status and UploadedDate
*/
var fields = [
"Id",
"Filename",
"Status",
"UploadedDate"
];
$(document).ready(function() {
$("#reqBtn").click(function() { // When the request button is clicked
// Request the JSON data
$.getJSON("URL_TO_FILE", function (data) {
// Create a variable to hold all the rows
var rows = "";
// For each object in the JSON data
$.each(data, function (index, value) {
// Add a new table row tag to the rows variable
rows += "<tr>";
// For all the fields you want to display
for (var i = 0; i < fields.length; i++) {
// Add the value to the row
rows += "<td>" + value[fields[i]] + "</td>";
}
// End the row tag
rows += "</tr>";
});
// Add the rows to the table body
$("#rows").html(rows);
});
});
});
</script>
谢谢,真是帮了! –
不要忘记将其标记为回答,如果它回答了你的问题。 – y0hami
加样JSON将有助于.... – Ashish451
很抱歉,现在更新@ Ashish451 –