我知道有很多关于用数据填充
Jquery
Datatables的答案和教程,但我总是得到以下异常:
Uncaught TypeError: Cannot read property ‘length’ of undefined
我,主要是一个后端开发人员,几乎没有编写客户端的经验,所以我想问你在下面的例子中我做错了什么.
我有一个本地运行的服务器暴露端点/目标,它以这种格式响应JSON字符串:
[{ "id": 1,"name": "London Heathrow","lat": 51.470022,"lon": -0.454295 },{ "id": 2,"name": "London Gatwick","lat": 51.153662,"lon": -0.182063 },{ "id": 3,"name": "Brussels Airport","lat": 50.900999,"lon": 4.485574 },{ "id": 4,"name": "Moscow Vnukovo","lat": 55.601099,"lon": 37.266456 }]
我想使用Datatables插件在表格中显示这些数据.这是表格代码:
<table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Lattitude</th> <th>Longitude</th> </tr> </thead> </table>
并填充脚本:
$(document).ready(function() { $('#example').DataTable({ "processing" : true,"ajax" : { "url" : ".../destination","type" : "GET" },"columns" : [ { "data" : "id" },{ "data" : "name" },{ "data" : "lat" },{ "data" : "lon" }] }); });
如上所述,我得到了Uncaught TypeError:无法读取未定义的属性“length”.任何帮助表示赞赏.
编辑:如果我请求数据然后将数据传递到数据表,它的工作原理如下:
$.ajax({ url : '/AOS-project/destination',type : 'GET',dataType : 'json',success : function(data) { assignToEventsColumns(data); } }); function assignToEventsColumns(data) { var table = $('#example').dataTable({ "bAutoWidth" : false,"aaData" : data,"columns" : [ { "data" : "id" },{ "data" : "name" },{ "data" : "lat" },{ "data" : "lon" } ] }) }
我期待数据表在…中烘焙此功能
解决方法
将dataSrc设置为”.正如
documentation所述:
Get JSON data from a file via Ajax,using dataSrc to read data from a
plain array rather than an array in an object:
$(document).ready(function() { $('#example').DataTable({ "processing" : true,"ajax" : { "url" : "https://api.myjson.com/bins/14t4g",dataSrc : '' },{ "data" : "lon" }] }); });
并且您的代码有效 – > http://jsfiddle.net/nzn5m6vL/