gpt4 book ai didi

javascript - 如何从 JSON 数组创建 jquery 数据表而不声明列

转载 作者:行者123 更新时间:2023-11-28 17:26:38 25 4
gpt4 key购买 nike

我有以下从 WebAPI 获取 JSON 的代码。(为了清楚起见,我已将数组定义为来自 Web API 的数据)。

我需要动态的数据表,这就是我在运行时创建表头的原因。

这工作正常,但我在数据表上看不到任何数据并收到错误:

DataTables warning: table id=tableId - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

var data = [{
"Number": "10031",
"Description": "GYPROCK PLUS RE 10MM 1200X4200",
"FarmLocation": "WH5",
"LocationIn": "LINE_1C2AA",
"Quantity": 18
},
{
"Number": "95844",
"Description": "CEMINSEAL WALLBOARD RE 6MM 1350X3000",
"FarmLocation": "WH5",
"LocationIn": "LINE_1C2AB",
"Quantity": 6
}
];

var $thead = $('#tableId').find('thead');
var tr = $("<tr>");
$thead.append(tr);
$.each(data[0], function(name, value) {

$(tr).append('<th>' + name + '</th>');
});

$('#tableId').DataTable({
data: data,
});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="tableId" class="table table-condensed responsive">
<thead>
</thead>
<tbody>

</tbody>
</table>

最佳答案

    var data = [{
"Number": "10031",
"Description": "GYPROCK PLUS RE 10MM 1200X4200",
"FarmLocation": "WH5",
"LocationIn": "LINE_1C2AA",
"Quantity": 18
}, {
"Number": "95844",
"Description": "CEMINSEAL WALLBOARD RE 6MM 1350X3000",
"FarmLocation": "WH5",
"LocationIn": "LINE_1C2AB",
"Quantity": 6
}];

var $thead = $('#tableId').find('thead');
var tr = $("<tr>");
$thead.append(tr);
var columns = [];
$.each(data[0], function(name, value) {
var column = {
"data": name,
"title":name
};
columns.push(column);
});

$('#tableId').DataTable({
data: data,
columns: columns
});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="tableId" class="table table-condensed responsive">
</table>

也许您可以尝试从数据创建列。但是,如果数据更新了,我想你需要以同样的方式刷新表格

关于javascript - 如何从 JSON 数组创建 jquery 数据表而不声明列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com