我尝试使用JSON使用动态列渲染数据表,但不断收到以下错误:
Uncaught TypeError: Cannot read property 'length' of undefined.
非常感谢任何帮助。
谢谢!
JS:
<link href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.css" rel="stylesheet" type="text/css"/>
<script src="http://cdn.datatables.net/1.10.4/js/jquery.dataTables.js" type="text/javascript"></script>
jQuery(document).ready(function() {
var dataObject = '[{"COLUMNS":[{ "sTitle": "NAME"}, { "sTitle": "COUNTY"}],"DATA":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]}]';
var columns = [];
jQuery.each(dataObject.COLUMNS, function(i, value){
var obj = { sTitle: value };
columns.push(obj);
});
jQuery('#example').dataTable({
"bProcessing": true,
"bPaginate": true,
"sPaginationType": "full_numbers",
"aaData": dataObject.DATA,
"aoColumns": columns
});
});
HTML:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<tr><thead>column1</thead></tr>
<tbody></tbody>
</table>
答案 0 :(得分:14)
嗨,代码中有几个问题...
jQuery(document).ready(function() {
var dataObject = eval('[{"COLUMNS":[{ "title": "NAME"}, { "title": "COUNTY"}],"DATA":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]}]');
var columns = [];
$('#example').dataTable({
"data": dataObject[0].DATA,
"columns": dataObject[0].COLUMNS
});
});
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
</table>
答案 1 :(得分:7)
我觉得用这个
可以让生活变得更轻松
jQuery(document).ready(function() {
var dataObject = {
columns: [{
title: "NAME"
}, {
title: "COUNTY"
}],
data: [
["John Doe", "Fresno"],
["Billy", "Fresno"],
["Tom", "Kern"],
["King Smith", "Kings"]
]
};
var columns = [];
$('#example').dataTable({
"data": dataObject.data,
"columns": dataObject.columns
});
});
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
答案 2 :(得分:1)
那些在https://datatables.net/tn/4上描述警告:请求未知错误的人,请检查您的json数据格式。以下示例可以帮助您。
var dataObject = eval('[{"columns":[{ "title": "Id", "data":"Id"}, { "title": "Name", "data":"Name"}],"data":[{"Id":"123","Name":"John Doe Fresno"}, {"Id":"124","Name":"Alice Alicia"}]}]');
$('#example').DataTable(dataObject[0]);
答案 3 :(得分:0)
您对dataObject的声明是针对String的,而不是具有属性“COLUMNS”和DATA的对象 - 删除末尾的'[在开头和'],所以你有这个(它将是一个对象):< BR />
var dataObject = {"COLUMNS":[{ "sTitle": "NAME"}, { "sTitle": "COUNTY"}],"DATA":[["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]};