JQuery Datatables without Array

99封情书 提交于 2019-12-11 07:17:56

问题


I'm having trouble populating a table, accessing a text file that has JSON like this:

{
    "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)"
    }
}

I have followed the examples on datatables.net and tried loading it on to my 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>

And the datatable.js is as simple as this

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

Can someone help me figure out where I have gone wrong with the code ?


回答1:


I managed to fix the issue by adding a custom function as part of dataSrc attribute (Thanks Jongyu Lin). Here is the change to my 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"
            }
        ]
    });
});


来源:https://stackoverflow.com/questions/26568942/jquery-datatables-without-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!