场景
我第一次使用datatables(@版本1.9.4)向用户显示数据。我成功通过ajax检索到数据并将其绑定到datatable上。
现在,我想添加额外的列以让用户处理记录。为了简单起见,目标是添加一个按钮和一个onclick处理程序,以检索“点击”记录的数据。
按照我的计划,我会将与“点击”记录对应的json项目绑定到onclick处理程序上。
到目前为止,如果我向DOM添加一个附加的TH
用于操作列,则datatables代码会出现错误:
Requested unknown parameter '5' from data source for row 0
问题
如何设置自定义列?如何使用HTML填充它们的内容?
这是我的实际配置。
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
示例Json结果
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
编辑
Daniel 是正确的。解决方案是在 aoColumnDefs
中设置自定义列,指定 mData
和 mRender
属性。特别地,mRender
允许定义自定义的 HTML 和 JavaScript。
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return '<a href="#" onclick="alert(\''+ full[0] +'\');">Process</a>';
}
}
]