无法将Json数据与Jquery data表绑定



下面是我从api调用中获得的json数据。

{   "data": [
{
"Id": "123",
"name": "fgfnnn",
"postCode": "123-456",
"Address": "test",
"street": "test3"
},
{
"Id": "456",
"name": "gggcgh",
"postCode": null,
"Address": null,
"street": null
}
]

}

我正试图绑定到下面的tblHospital表,但出现错误。

jQuery('#tblHospital').DataTable({
data: JSON.parse(res),
columns: [
{ "data": "name" }
{
"data": "address",

"render": function (data, type, full, meta) {
return data.Address +  data.street + data.postCode;
}
},
]
}); 

有人能帮忙吗?错误类似于DataTables警告:表id=tblHospital-为第0行第0列请求了未知参数"name"。有关此错误的详细信息,请参阅http://datatables.net/tn/4

欢迎使用StackOverflow。

数据表的选项中存在一些配置错误。

首先,您的对象格式不正确。您没有在正确的位置关闭或添加逗号。

其次,您写了address,但您的对象有一个大写的AAddress

第三,不能在渲染函数中使用data.Address,因为它只是单元的值。您需要获得行的值(在您的情况下,它应该是full.Address(

你可以运行下面的代码,你会看到它的工作。

var data = [{
"Id": "123",
"name": "fgfnnn",
"postCode": "123-456",
"Address": "test",
"street": "test3"
},
{
"Id": "456",
"name": "gggcgh",
"postCode": null,
"Address": null,
"street": null
}
];

$(document).ready(function() {
$('#tblHospital').DataTable({
data: data, //Here you'll have to keep JSON.parse(res). I had to change it since my values are in a variable above for this example to work.
columns: [
{ "data": "name" }, 
{ "data": "Address", 
"render": function ( data, type, row, meta ) {
return row.Address + ' ' + row.street + ' ' + row.postCode;
}
}
]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="tblHospital" class="display">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

尝试使用ajax而不是data。并用ajax调用API。

jQuery('#tblHospital').DataTable({
"ajax": //API call here,
"columns": [
{ "data": "name" },
{
"data": "address",             
"render": function (data, type, full, meta) {
return data.Address +  data.street + data.postCode;
}
},
]
});

最新更新