如何在不声明列的情况下从JSON数组创建jquery数据表 [英] How to create jquery data table from JSON array without declaring columns

查看:82
本文介绍了如何在不声明列的情况下从JSON数组创建jquery数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have following code which gets JSON from WebAPI.(for clarity of the question, I have defined the array as data from web API).

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

I need the data table to be dynamic and that's why I am creating the table headers at run time.

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

This works fine, but I do not see any data on data table and get the error:

DataTables警告:表id = tableId-请求的未知参数'0'用于第0行第0列.有关此错误的更多信息,请参见 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>

也许您可以尝试根据数据创建列. 但是,如果数据已更新,我想您需要以相同的方式刷新表

Maybe you can try to create the column from the data. However, if the data is updated, I suppose you need to refresh the table in same way

这篇关于如何在不声明列的情况下从JSON数组创建jquery数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆