JQuery的数据表,而不阵列(JQuery Datatables without Array)

2019-09-27 13:38发布

我无法填充表,访问具有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" }
        ]
    } );
} );

有人可以帮我找出哪里出了毛病的代码?

Answer 1:

我设法通过添加自定义功能DATASRC属性(感谢Jongyu林)的一部分来解决该问题。 这里是改变我的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"
            }
        ]
    });
});


文章来源: JQuery Datatables without Array