简体   繁体   中英

Dynamically set datasource for jquery datatable columns

Is there a way we can dynamically set data source of datatable columns? Like I set columns.data by hardcoding each property name like this:

$.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:

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:

var obj=array[0];
var keys=[];
for(var k in obj) 
    keys.push({"data":k});

Now, keys array looks like this:

[
   {"data":"PName"},
   {"data":"PTime"}
]

And the last step is to assign array to columns property of DataTable :

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. Is used a php function to loop through the headers and put it into a json array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM