问题
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