[英]how to render columns from `dataSrc` function in datatable?
i want to show data from API into datatable using AJAX Request, this is my API response:我想使用 AJAX 请求将 API 中的数据显示到数据表中,这是我的 API 响应:
{
"title": "success",
"data": {
"name": "yogi",
"email": "yogi@gmail.com",
"activity": [
{
"name": "pergi"
},
{
"name": "belanja"
},
{
"name": "makan"
},
{
"name": "tidur"
}
]
}
}
and this is my datatable script:这是我的数据表脚本:
$(document).ready(function () {
$("#activity-list").DataTable({
processing: true,
serverSide: true,
ajax: {
url: `${baseurl}/api/user/${user_id}/activity`,
dataSrc: function (json) {
let results = [];
for (let i = 0; i < json.data.activity.length; i++) {
results.push({
name: json.data.name,
email: json.data.email,
activity: json.data.activity[i].name,
});
}
return results;
},
},
});
});
why the data doesn't appear, instead i got error message?为什么数据没有出现,而是我收到错误消息?
The only thing you are missing is the columns
option, which maps your results
array to the HTML table's columns:您唯一缺少的是
columns
选项,它将您的results
数组映射到 HTML 表的列:
$("#activity-list").DataTable({
processing: true,
serverSide: true,
columns: [
{ data: "name" },
{ data: "email" },
{ data: "activity" }
],
ajax: {
url: '[my test URL here]',
dataSrc: function (json) {
let results = [];
for (let i = 0; i < json.data.activity.length; i++) {
results.push({
name: json.data.name,
email: json.data.email,
activity: json.data.activity[i].name,
});
}
return results;
}
}
});
This assumes you have a HTML table defined which already has the column headers you want to display:这假设您定义了一个 HTML 表,该表已经具有您要显示的列标题:
<table id="activity-list" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Activity</th>
</tr>
</thead>
</table>
(Or, you could add those headings to the DataTables columns
option using title
, if you prefer.) (或者,如果您愿意,可以使用
title
将这些标题添加到 DataTables columns
选项。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.