【发布时间】:2014-10-15 16:20:38
【问题描述】:
由于DataTable 中有超过 20k~ 项要显示,我想根据一些参数填充它以避免大滞后。
// Clears the DataTable to avoid duplication of items
$('#contacts-table > tbody').empty();
var category_id = 5; // Just for tests
$.post('ajax_getAll', {category_id: category_id}, function(response){
// I retrieve the 'response' as json_encoded
var json = JSON.parse(response);
});
如果我不使用DataTables,我会按照传统方式(填充tbody):
$.each(json, function(index, item){
var tr = "<tr>";
tr += " <td><input type='checkbox' class='checkbox'/></td>";
tr += " <td>" + item.id + "</td>";
tr += " <td>" + item.name + "</td>";
tr += "</tr>";
$('#contacts-table').prepend(tr);
});
但是,使用这段代码,虽然项目已成功检索并插入到 DataTable 中,但 DataTable 的功能(如重新排序、搜索等)停止工作,当我使用这些功能时,它会自动删除我的所有表tbody.
所以我搜索了一下,发现应该使用 Data attribute 填充 DataTable。
// Since I've initialized the DataTable in the load of the jQuery
// I must destroy it so I can re-load it again
$('#contacts-table').DataTable().destroy();
$('#contacts-table').DataTable({
'bPaginate': true,
'bLengthChange': false,
'bFilter': true,
'bInfo': true,
'bAutoWidth': true,
"iDisplayLength": 30,
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['nosorting']
}],
"aaSorting": [],
'data': json, // Here I'm trying to pass the values without any success
});
使用最后一个代码,我收到此错误Warning: Request unknown
我从 PHP 收到的 json 如下:
[{"id":"16","name":"just testing"}, {"id":"16","name":"stackoverflow"}]
除了我收到的错误之外,我想知道如何使用DataTables by ajax 设置此tr += " <td><input type='checkbox' class='checkbox'/></td>";。
【问题讨论】:
标签: php jquery ajax codeigniter datatable