具有动态列的数据表 [英] DataTables with Dynamic Columns

查看:72
本文介绍了具有动态列的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON呈现具有动态列的数据表,但始终出现以下错误:

I'm trying to render a datatable with dynamic columns using JSON but keep getting the following error:

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>

推荐答案

代码中有几个问题...

Hi there are several issue in the code...

  • dataObject是字符串,而不是json.因此您可以使用eval()或删除'
  • 使其成为json对象
  • 您在数据表中传递的参数名称错误.您需要提供准确的参数.
  • 您正在使用父json对象作为数组.但是您没有使用[]来获取其第一个元素.
  • 您的html内容是表格错误.因为您正在使用Java脚本传递列名.您不需要html表标题.由于此html代码而实际发生的长度错误.如果您删除表格内的html,则您的代码将不会出现长度错误.但是上面提到的错误仍然存​​在.请检查下面的代码.可能您正在寻找此代码...
  • dataObject is string, not a json. so you can make it json object using eval() or removing '
  • the parameter name you are passing in datatable is wrong. you need to provide the accurate parameter.
  • You are using the parent json object as array. but you are not using [] to get its first element.
  • your html content is the table is wrong. since you are passing the columns name using java script. you dont need the html table headers. the length error actually occurring because of this html code. if you remove the html inside the tables then your code will not have the length error. but still the above error i mentioned will be there. please check the code bellow. may be you are looking for this code...

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>

这篇关于具有动态列的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆