遇到数据表列问题。我试图动态创建列数据选项但不起作用。如果我对列进行硬编码就可以了。
这最终将使用Ajax作为数据,我永远不会知道返回的列或数据,并且必须是完全动态的。
Getting Error: Timestamp: 4/6/2015 1:00:27 PM Error: TypeError: invalid 'in' operand a Source File: http://52.4.158.201/js/jquery-2.1.1.min.js Line: 2
HTML
<table id="example2">
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
Javascript
$(document).ready(function()
{
var dataTest = '{"header": ["Name","Position","Office","Age","Start_date","Salary"],"staff": [{"name":"Tiger Nixon","position":"System Architect","office":"Edinburgh","age":61,"Start_date":"2011/04/25","salary":"$320,800"},{"name":"Garrett Winters","position":"Accountant","office":"Tokyo","age":63,"Start_date":"2011/07/25","salary":"$170,750"},{"name":"Ashton Cox","position":"Junior Technical Author","office":"San Francisco","age":66,"Start_date":"2009/01/12","salary":"$86,000"}]}';
var obj = JSON.parse(dataTest);
for(var i = 0; i < obj.header.length; i++)
{
$('#example2 thead tr').append('<th>' + obj.header[i] + '</th>');
}
var dtColumns = '';
var c = 0;
for (var prop in obj.staff)
{
if(c == 0)
{
for(var key in obj.staff[prop])
{
dtColumns = dtColumns + '{"data":"'+ key +'"},';
}
}
else
{
break;
}
c++;
}
dtColumns = dtColumns.replace(/,+$/,'');
//console.log(dtColumns);
$('#example2').DataTable({
data: obj.staff,
columns: [dtColumns]
});
/*
* WORKS
*/
/*
var table2 = $('#example2').DataTable({
data: obj.staff,
columns: [
{'data':'name'},
{'data':'position'},
{'data':'office'},
{'data':'age'},
{'data':'Start_date'},
{'data':'salary'}
]
});
*/
//table2.rows.add(obj.staff).draw();
});