没有数组的JQuery数据表

时间:2014-10-26 01:28:21

标签: json jquery-datatables

我无法填充表格,访问具有JSON的文本文件,如下所示:

{
    "1000": {
        "country": "US",
        "eventid": 1000,
        "venue": "San Francisco, USA"
    },
    "2000": {
        "country": "DE",
        "eventid": 2000,
        "venue": "Munich, Germany"
    },
    "3000": {
        "country": "GB",
        "eventid": 3000,
        "venue": "UK (Market House)"
    }
}

我已经关注了datatables.net上的示例,并尝试将其加载到我的HTML

<HTML>
    <head>
        <title>Hello World</title>
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css"/>
        <link rel="stylesheet" type="text/css" href="dataTables.bootstrap.css"/>
        <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
        <script type="text/javascript" src="jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="datatable.js"></script>
        <script type="text/javascript" src="dataTables.bootstrap.js"></script>
    </head>
    <body>
        <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>Country</th>
                    <th>Event</th>
                    <th>Venue</th>
                </tr>
            </thead>
        </table>
    </body>
</html>

datatable.js就像这个

一样简单
$(document).ready(function() {
    $('#example').dataTable( {
        "processing": true,
        "ajax": 'sample.txt',
        "columns": [
            { "country" },
            { "eventid" },
            { "venue" }
        ]
    } );
} );

有人可以帮我弄清楚代码出错了吗?

1 个答案:

答案 0 :(得分:1)

我设法通过添加自定义函数作为dataSrc属性的一部分来解决问题(感谢Jongyu Lin)。这是对我的Javascript的更改

$(document).ready(function () {
    $('#example').dataTable({
        "processing": true,
        "ajax": {
            "url": 'json.txt',
            "dataSrc": function (json) {
                var arr = Object.keys(json).map(function(k) { return json[k] });
                return arr;
            }
        },
        "columnDefs": [
            {
                "targets": [2],
                "visible": true,
                "searchable": true
            }
        ],
        "columns": [
            {
                "data": "eventid"
            },
            {
                "data": "country"
            },
            {
                "data": "venue"
            }
        ]
    });
});