javascript - Load Data into datatable where i dont know the columns -
i creating datatable fetching data database using ajax response.
i getting following jason data
[ { "id": "11105", "name": "gummy drop (iphone, free, row except cn, 72.3mb, w" }, { "id": "11107", "name": "gummy drop (ipad, free, row except cn, 72.3mb, w/ " }, { "id": "4274", "name": "z-redirect non-targeted traffic dragon city mobile" }, { "id": "6484", "name": "z-redirect non-targeted traffic dragon city mobile" } ]
the issue is, may not know data coming ajax response
so extracting keys of json array create header, in suceesfull in doing so.
let me share code, easy understand , explain
$('#load').click(function() { var v = $('#drp_v').val(); var cnt = $('#drp_cnt').val(); var ctg = $('#drp_ctg').val(); alert("version :"+v+" category :"+ctg+" country :"+cnt); $.post("ajax.php",{'version':v,'category':ctg,'country':cnt,'func':'show_datatable'}, function(data) { var acolumns = []; var columns = []; for(var = 0; < data.length; i++) { if(i>0) break; keycolumns = object.keys(data[i]); for(j = 0; j < keycolumns.length; j++) { alert(keycolumns[j]); if($.inarray(keycolumns[j],acolumns.stitle)<=0) { acolumns.push({stitle: keycolumns[j]}) //checks if columns.push(keycolumns[j]) //checks if } } } var otable = $('#jsontable').datatable({ "columns":acolumns, "sdom": 't<"clear">lfrtip', "otabletools": { "abuttons": [ { "sextends": "csv", "sbuttontext": "csv", } ] } }); otable.fncleartable(); for(var = 0; < data.length; i++) { for(var c = 0; c < columns.length; c++) { otable.fnadddata([ data[i].columns[c]]); } } },'json'); });
as u can see, var columns = [];
actualy contains key of json array getting
so value of var columns
this
['id','name','description']
;
so if assume id,name , description 3 keys, instead of using code
for(var = 0; < data.length; i++) { otable.fnadddata([ data[i].id, data[i].name, data[i].description]); }
i have used code
for(var = 0; < data.length; i++) { for(var c = 0; c < columns.length; c++) { otable.fnadddata([ data[i].columns[c]]); } }
so data can loaded dynamic key values stored in var columns.
but think made mistake. can me in corecting wrong have done?
use code :
var row = [] for(var = 0; < data.length; i++) { for(var c = 0; c < columns.length; c++) { row.push( data[i][columns[c]] ) ; } otable.fnadddata(row); row = []; }
Comments
Post a Comment