我正在尝试设置 jQuery DataTables。我所需要的只是简单地在表中显示一些 JSON 数据。
这是我的 JS 代码。我知道 myObj 已经是一个 JSON 对象,但为了安全起见,我通过 JSON.stringify 传入,因为我对此失去了理智。
var myObj = { "name":"John", "age":31, "address":"123 Street","city":"New York" };
var data = JSON.stringify(myObj);
$(document).ready(function() {
$('#table').DataTable( {
"ordering": true,
"data": data,
"searching": false,
"columns": [
{'data':'name'},
{'data':'age'},
{'data':'address'},
{'data':'city'}
]
});
});
HTML代码:
<html>
<head>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/style.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/b-1.2.4/b-html5-1.2.4/b-print-1.2.4/fh-3.1.2/r-2.1.1/sc-1.4.2/datatables.min.css" />
</head>
<body>
<table id="table" class="table table-hover">
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/b-1.2.4/b-html5-1.2.4/b-print-1.2.4/fh-3.1.2/r-2.1.1/sc-1.4.2/datatables.min.js"></script>
<script src="assets/js/dataLoader.js"></script>
</body>
</html>
我不是最擅长格式化,但你懂的。上面的JS代码在dataLoader.js文件中。问题是我在运行 html 文件时收到此 dataTables 错误。
我真的很困惑为什么它不知道名字是什么。如果我运行
console.log(data.name)
,它会返回 John。为什么不显示数据? 最佳答案
类型应该是一个数组。请参阅 data option 文档中的 类型 标题:
您看到的错误是数据表代码尝试将单个对象作为数据数组处理的结果。
因此,不要将 JSON.stringify()
的值分配给 data
,而是将 data
设为一个包含 myObj 的数组(将来,可以将更多对象添加到该数组中):
var data = [myObj];
请参阅下面应用的更改:
var myObj = { "name":"John", "age":31, "address":"123 Street","city":"New York" };
var data = [myObj];//JSON.stringify(myObj);
$(document).ready(function() {
$('#table').DataTable( {
"ordering": true,
"data": data,
"searching": false,
"columns": [
{'data':'name'},
{'data':'age'},
{'data':'address'},
{'data':'city'}
]
});
});
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/style.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/b-1.2.4/b-html5-1.2.4/b-print-1.2.4/fh-3.1.2/r-2.1.1/sc-1.4.2/datatables.min.css" />
<table id="table" class="table table-hover">
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/b-1.2.4/b-html5-1.2.4/b-print-1.2.4/fh-3.1.2/r-2.1.1/sc-1.4.2/datatables.min.js"></script>
1 https://datatables.net/reference/option/data
关于javascript - JQuery DataTables - 不显示数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42639372/