gpt4 book ai didi

javascript - 如何使用 Ajax 在数据表数组上显示数据?

转载 作者:行者123 更新时间:2023-12-02 23:11:01 25 4
gpt4 key购买 nike

我正在使用 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

我该如何解决这个问题?我正在考虑使用 foo 循环,但我真的不知道该怎么做,因为我直接在 table 变量中调用数据。

json 响应是这样的:

{"data":"[[11756.53, 2.419583] .....

最佳答案

您正在使用数组的数组数据,只需使用索引键来映射您的列:

"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>

关于javascript - 如何使用 Ajax 在数据表数组上显示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57362130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com