javascript - Datatables ajax 回调不填充表
问题描述
我很少使用 javascript,所以我很确定这要么是错误配置,要么是我遗漏的东西。
我正在使用Datatables v1.10.7
. 我有一个表,其中包含所有必需的 pars、 athead
和tfoot
a tbody
。以该顺序。
我正在使用服务器端处理来获取一些数据并填充表格。
由于我想添加一些与数据表无关但与它获得的数据相关的其他内容,我想要一个回调函数。
$('#target-list-li').DataTable({
processing: true,
serverSide: true,
pageLength: 100,
ajax: {
url: ajax_url,
success: function(data) {
// Do other stuff here
return data;
}
},
columns: [
{
data: 'trans_source_id',
render: function (data, type, row) {
var html = '';
html += '<input type="checkbox" id="check-' + row.trans_source_id + '" ';
},
orderable: false
},
// more columns would go here but I've removed them since it's irrelevant to the question
});
“问题”或对它的误解可能是与这段代码有关success: function(data)
。
我希望能够对数据做一些工作,然后返回数据。请注意,无论如何我都不会更改原始数据,我只是想从中提取一些信息。
success: function(data) {
// Some some stuff here
return data;
}
然而,这根本不起作用。即使我只是返回数据,表格也不会被填充。事实上,它只是挂在 ajax 调用上。它确实完成了,但没有填充任何内容。
ajax 的推荐 go to 选项显然是dataSrc
. 文件是这样说的
dataSrc: function(data) {
return data;
}
这确实“有点”工作,表中没有数据填充,至少它是对success
.
这就是我的表与dataSrc
属性的外观。
文档对此充其量是模糊的,或者至少我似乎找不到与我的问题相关的东西。
我期望发生的是:进行 ajax 调用,将数据用于一些回调,同时不改变原始数据。做我的事,返回原始数据,就是这样。
显然这里不是这种情况。
如果有人可以在这里直接指出我的正确位置,我将不胜感激。
解决方案
我曾使用Datatables插件处理过一个项目,其常用方法是:
1)首先获取ajax post
到服务器的数据。
2)data
一旦服务器success
响应table
.
对于您拥有的代码示例,该方法将是这样的:
// First, make an ajax post to get data from the server.
$.ajax({
type: "POST", /* You could use GET if the server support it */
dataType: "json" /* Use the adequate type for your case */,
url: ajax_url,
success: function(data)
{
// Log the data to check the structure.
console.log(data);
// Pre-process data here...
// Create and render the datatable.
// We assume, "data.data" holds the source data for the table.
createDatatable(data.data);
},
error: function()
{
alert('Failed to get data from server');
}
});
// Method for create and render the datatable.
function createDatatable(srcData)
{
$('#target-list-li').DataTable({
pageLength: 100,
data: srcData,
columns: [
{
data: 'trans_source_id',
render: function (data, type, row)
{
var html = '';
var sId = row.trans_source_id;
html += '<input type="checkbox" id="check-' + sId + '" ';
},
orderable: false
},
// More columns would go here but I've removed them since
// it's irrelevant to the question.
],
});
}
推荐阅读
- python - 是否可以使类的实例可调用
- php - 从单个数组中创建多个 PHP 数组并将这些新数组存储到新的单个数组中
- java - 如果 EditText 值为 true,如何将 1 添加到分数
- c# - 在从文本运行时编译类时使用 ValueTuple
- c# - 如何从 Xamarin Forms 的 ContentPage 中保存 App.xaml 中的资源?
- c# - 我在执行 selenium(C#) 脚本时面临“TypeInitializationException”
- c# - Python3、OpenCV 和 C#
- html - 为什么 min-height 在父 div 上不起作用?
- html - 为什么我的文本垂直而不是水平对齐?
- c++ - Getline 未读取 CSV 文件 C++ 的整行