【发布时间】:2017-02-28 22:21:31
【问题描述】:
请有人建议我如何在 JQuery 数据表上使用 AJAX 选项。我目前正在使用 AJAX 检索数据,然后将其作为数据变量传递,以便在设置表时使用:
$table = $('#cat_content_datatable').DataTable ( {
select: {
style: 'single'
},
data:data,
"bFilter": false, // remove search filter
"order": [],
responsive: true,
columns: [
{ 'data': null },
{ 'data': 'content_id' },
{ 'data': 'employer' }
],
"columnDefs": [
{
"targets": -3,
"orderable": false,
"data": null,
"defaultContent": "<button type = 'button' class='btn btn-xs btn-primary'>Select</button>"
},
{
"targets": [ 1 ],
"visible": false,
"searchable": false
}
]
});
这很好,但我想在数据表上使用 AJAX 重新加载选项。
传递给表的数据是:
[{"content_id":"47","employer":"ADAS"}]
我已经尝试过文档AJAX option 并正在调用以下函数:
function populateCatEmpDT (catDesc, catID, action) {
$table = $('#cat_content_datatable').DataTable ( {
select: {
style: 'single'
},
ajax: {
url: '../workflow_ajax/fields/ajax.php',
method: 'GET',
data: {catDesc: catDesc, catID:catID, emp:'BT', action: action},
dataType: 'json',
type: 'POST'
},
"bFilter": false, // remove search filter
"order": [],
responsive: true,
columns: [
{ 'data': null },
{ 'data': 'content_id' },
{ 'data': 'employer' }
],
"columnDefs": [
{
"targets": -3,
"orderable": false,
"data": null,
"defaultContent": "<button type = 'button' class='btn btn-xs btn-primary'>Select</button>"
},
{
"targets": [ 1 ],
"visible": false,
"searchable": false
}
]
});
}
我可以从控制台看到我正在检索相同的数据:
[{"content_id":"47","employer":"ADAS"}]
但数据表本身只是说“正在加载...”并且在控制台中我收到一个错误:
TypeError: f 未定义
有人可以帮忙吗?非常感谢。
Bindrid,感谢您的帮助,并对延迟回复表示歉意。最后我使用了以下代码:
function populateTooltipDT(contentID) {
$table = $('#tooltip_datatable').DataTable ( {
select: {
style: 'single'
},
destroy: true,
ajax: {
url: '../workflow_ajax/tooltips/ajax.php',
type: 'POST',
data: {contentID: contentID},
dataType: 'json',
dataFilter: function(data){
// DataFilter is where you can change the json data format from what your server sends to
// what DataTable expects.
// if your data is serialized at this point, deserialize it
var jData = JSON.parse(data);
// then what the DataTables expect and reserialize
var dtData =JSON.stringify( {"data": jData});
console.log(dtData);
return dtData;
}
},
"bFilter": false, // remove search filter
"order": [],
responsive: true,
columns: [
{ 'data': null },
{ 'data': 'id' },
{ 'data': 'keyword' },
{ 'data': 'tip' },
{ 'data': null }
],
"columnDefs": [
{
"targets": -5,
"orderable": false,
"data": null,
"defaultContent": "<button type = 'button' class='btn btn-xs btn-warning'>Edit</button>"
},
{
"targets": [4],
"orderable": false,
"data": null,
"defaultContent": "<button type = 'button' class='btn btn-xs btn-danger'>Delete</button>"
},
{
"targets": [ 1 ],
"visible": false,
"searchable": false
}
]
});
}
【问题讨论】:
-
类型和方法是一回事,一个是另一个的别名,所以它们应该是一样的。 api.jquery.com/jQuery.ajax
-
另外,我必须将我的数据放在一个名为 data 的对象中,以便 DataTable 自动处理它,除非您将 DataTable 的 dataSrc 属性设置为指向不同的对象
-
感谢 Bindrid。如何将它放在一个名为 data 的对象中?抱歉......这对我来说有点学习曲线!
标签: jquery datatables