[英]Dynamically set datasource for jquery datatable columns
Is there a way we can dynamically set data source of datatable columns? 有没有一种方法可以动态设置datatable列的数据源? Like I set
columns.data
by hardcoding each property name like this: 就像我通过像这样对每个属性名称进行硬编码来设置
columns.data
:
$.ajax({
data: JSON.stringify(data),
url: urlGetProviderQualificationTimeData,
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (obj) {
if (obj.success) {
$('#tblProds').dataTable({
data: obj.data.ProdsDetails,
columns: [
{ "data": "PName" },
{ "data": "PTime" } //hardcoded mapping of properties
]
});
}
},
});
ProdsDetails
sample array: ProdsDetails
示例数组:
Array[2]
0:Object
PName:"ATT",
PTime:"6.48"
1:Object
PName:"CENTURYLINK",
PTime:"3.67"
Is there a way we can get rid of this hardcoded mapping of properties and columns? 有没有办法摆脱这种对属性和列的硬编码映射?
Here is your array : 这是您的数组:
var array=[
{PName:"ATT",PTime:"6.48" },
{PName:"CENTURYLINK",PTime:"3.67"}
];
Now, You should get all the keys
and build final array: 现在,您应该获得所有
keys
并构建最终数组:
var obj=array[0];
var keys=[];
for(var k in obj)
keys.push({"data":k});
Now, keys
array looks like this: 现在,
keys
数组如下所示:
[
{"data":"PName"},
{"data":"PTime"}
]
And the last step is to assign array to columns
property of DataTable
: 最后一步是将数组分配给
DataTable
columns
属性:
columns:keys
Now this should look like this: 现在看起来应该像这样:
columns:[
{ "data": "PName" },
{ "data": "PTime" }
]
Hope this helps !. 希望这可以帮助 !。
I had the same problem and worked around this by creating an extra json
array for the columns.data
property. 我有同样的问题,并通过为
columns.data
属性创建一个额外的json
数组来解决此问题。 Is used a php
function to loop through the headers and put it into a json
array. 用于通过
php
函数遍历标头并将其放入json
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.