我正在使用MongoDB数据库存储一些数据。我现在想在HTML数据表上显示这些数据。
我要使用的数据存储在数组中,结构如下:
data: [[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]
$(document).ready(function() {
var table = $('#mytable').DataTable({
"serverSide": true,
"ajax": "/endpoint/?format=datatables",
"columns": [
{"data": 'data'},
]
});
setInterval( function () {
table.ajax.reload();
}, 10000 );
});
我的实际代码的问题是它将显示如下数据表:
DATA:
[[1848, 84857], [4944, 4949], [34, 65], [3566, 78], .... ]
我想这样:
DATA:
1848, 84857
4944, 949
36, 65 and so on
如何解决此问题?我当时正在考虑使用foor循环,但是我真的不知道该怎么做,因为我直接在table
变量中调用了数据。
json响应如下:
{"data":"[[11756.53, 2.419583] .....
答案 0 :(得分:1)
您正在使用数组数组数据,只需使用索引键即可映射您的列:
"columns": [
{"data":0},
{"data":1}
]
以下很棒的示例:
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
$.mockjax({
url: "/endpoint/?format=datatables",
response: function(settings) {
this.responseText = {
"draw": settings.data.draw,
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
[randomIntFromInterval(400, 8000), 84857],
[4944, 4949],
[34, 65],
[3566, 78]
]
}
}
});
var editable=false;
$(document).ready(function() {
var table = $('#mytable').DataTable({
"serverSide": true,
"ajax": "/endpoint/?format=datatables",
"columns": [
{"data":0},
{"data":1}
]
});
setInterval( function () {
table.ajax.reload();
}, 10000 );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="mytable" class="display nowrap" width="100%">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Col1</th>
<th>Col2</th>
</tr>
</tfoot>
</table>