jQuery 从 ajax json 填充数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39693168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate Datatable from ajax json
提问by Dallas
My table is not populating. I can see that it is getting the correct JSON
我的表没有填充。我可以看到它正在获取正确的 JSON
JSON Data received looks like this:
收到的 JSON 数据如下所示:
[
{
"id": "1",
"name": "FooBar",
"predicted": "0",
"points": "1",
"section_id": "1",
"detail_alias": ""
...
},
...
]
HTML
HTML
<table id="example"></table>
JS
JS
$('#example').dataTable( {
"ajaxSource": "rest/index.php?m=foo",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "detail_alias" },
{ "data": "points" }
]
} );
All I'm seeing in my browser is:
我在浏览器中看到的是:
It says "Loading..." when the network tab shows that the call had a 200 response with the correct data.
当网络选项卡显示该呼叫具有正确数据的 200 响应时,它会显示“正在加载...”。
Why isn't the table populating?
为什么表没有填充?
回答by Dallas
So the ajaxSource
in my question was expecting data to be formatted as such:
所以ajaxSource
我的问题是期望数据被格式化为:
{ data: [ { ...
{ data: [ { ...
And I didn't want to have to modify my back end to send data in this format as it would cause problems in other places. I'm assuming other people that end up on this page looking for a solution will likely have the same issue.
而且我不想修改我的后端以这种格式发送数据,因为它会在其他地方引起问题。我假设最终在此页面上寻找解决方案的其他人可能会遇到同样的问题。
My solution was to get the data via jQuery.ajax()
and then pass it in to the aaData
field, like this:
我的解决方案是通过获取数据jQuery.ajax()
,然后将其传递给aaData
字段,如下所示:
$.ajax({
'url': "/rest/index.php?m=foo",
'method': "GET",
'contentType': 'application/json'
}).done( function(data) {
$('#example').dataTable( {
"aaData": data,
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "detail_alias" },
{ "data": "points" }
]
})
})
This allows me to not have to worry about changing the json data from the format in the question.
这使我不必担心从问题中的格式更改 json 数据。
I like this way better anyway as I feel it gives me more flexibility if I wanted to do modify or use the data for anything else at the same time.
无论如何,我更喜欢这种方式,因为我觉得如果我想同时修改或将数据用于其他任何事情,它会给我更大的灵活性。
回答by Poldo
I think you must return your json with the array of "aaData"
我认为你必须用“aaData”数组返回你的json
return dataTabledata['aaData'] = 'your json data'
By default DataTables will use the "aaData" property of the returned data which is an array of arrays with one entry for each column in the table.
默认情况下,DataTables 将使用返回数据的“aaData”属性,这是一个数组数组,表中的每一列都有一个条目。
In your jQuery create ajax that will handle the data from your server side
在您的 jQuery 中创建 ajax,它将处理来自您的服务器端的数据
function getdtData(){
/*clear table row first*/
$('#sample').dataTable().fnDestroy();
/*populate your datatable using ajax*/
$('#sample').dataTable({
"sDom": 'frtip',
"bServerSide": true,
/*server side source*/
"sAjaxSource": "rest/index.php?m=foo",
/* we use sDom to specify the lenght of the pagination if you will using pagination in your data table*/
"lengthMenu": [[ 5, 5], [ 5, 5]],
"aoColumnDefs": [
{ "aTargets": [ 0 ], "bSortable": false},
{ "aTargets": [ 1 ], "bSortable": false },
{ "aTargets": [ 2 ], "bSortable": false },
{ "aTargets": [ 3 ], "bSortable": false }
]
});
refer to this documentation http://legacy.datatables.net/usage/server-side
回答by nyedidikeke
The table is not populating because you have no data
object in your received JSON data but referencing it (data
object)for display in the table columns.
该表未填充,因为data
您收到的 JSON 数据中没有对象,但引用它(data
对象)以在表列中显示。
Based on your dataTable initialisation, your JSON data should look like this:
根据您的 dataTable 初始化,您的 JSON 数据应如下所示:
{"data":[
{
"id": "1",
"name": "FooBar",
"predicted": "0",
"points": "1",
"section_id": "1",
"detail_alias": ""
...
},
...
]}
回答by Daniela Solis
Had the same problem while using codeigniter json_encode tipe of data, it returned a Flat array data sourceafther a few days of trying
使用 codeigniter json_encode 数据时遇到同样的问题,经过几天的尝试,它返回了一个平面数组数据源
"aaData": data,
“aaData”:数据,
i finaly got it working using
我终于让它工作了
"ajax": { "url": "index.php/controller/function", "dataSrc": "" },
"ajax": { "url": "index.php/controller/function", "dataSrc": "" },
instead of
代替
"data": [ [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
“数据”:[[“老虎尼克松”,“系统架构师”,“爱丁堡”,“5421”,“2011/04/25”,“$320,800”],
, in reality it is quite simple see datatble ajax documentation
,实际上它很简单,请参阅 datatble ajax 文档
$(document).ready(function() {
$('#t1').DataTable( {
"ajax": {
"url": "<?php echo base_url(); ?>index.php/controller/function",
"dataSrc": ""
},
"columns": [
{ "data": "CCODIGOCLIENTE" },
{ "data": "CRAZONSOCIAL" },
{ "data": "PENDIENTE" },
{ "data": "siete" },
{ "data": "sietev" },
{ "data": "catorcev" },
{ "data": "catorce" },
{ "data": "veintiunov" },
{ "data": "veintiuno" },
{ "data": "mes" },
{ "data": "bimestre" },
{ "data": "trimestre" }
]
} );
} );
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<table id="t1" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>QTime</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
a few pointers for begginers...
给初学者的一些提示......
- make sure your script is below you libraries
- that the number of columns matches your data
- make your datatable id unique
- 确保你的脚本在你的库下面
- 列数与您的数据匹配
- 使您的数据表 ID 唯一
good luck yaall
祝你好运
回答by user3708054
Js Code Where json url : getjsonrequest.php
Js 代码其中 json url : getjsonrequest.php
`
`
$(document).ready(function() {
$('#tableid').DataTable( {
"ajax": {
"url": "getjsonrequest.php",
"dataSrc": ""
},
"columns": [
{ "data": "INDEX1" },
{ "data": "INDEX2" }
]
} );
} );
`
`
Html Code
html代码
`
`
<table id="tableid" class="display" style="width:100%">
<thead>
<tr>
<th>Index 1</th>
<th>Index 2</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Index 1</th>
<th>Index 2</th>
</tr>
</tfoot>
</table>
`
`
回答by Hannah Benhamou
var $table = $('#productListTable');
// execute the below code only where we have this table
if($table.length) {
//console.log('Inside the table!');
var jsonUrl = '';
if(window.categoryId == '') {
jsonUrl = window.contextRoot + '/json/data/all/products';
}
else {
jsonUrl = window.contextRoot + '/json/data/category/'+ window.categoryId +'/products';
}
$table.DataTable( {
lengthMenu: [[3,5,10,-1], ['3 Records', '5 Records', '10 Records', 'ALL']],
pageLength: 5,
ajax: {
url: jsonUrl,
dataSrc: ''
},
columns: [
{
data: 'code',
bSortable: false,
mRender: function(data, type, row) {
return '<img src="'+window.contextRoot+'/resources/images/'+data+'.jpg" class="dataTableImg"/>';
}
},
{
data: 'name'
},
{
data: 'brand'
},
{
data: 'unitPrice',
mRender: function(data, type, row) {
return '₹ ' + data
}
},
{
data: 'quantity',
mRender: function(data, type, row) {
if(data < 1) {
return '<span style="color:red">Out of Stock!</span>';
}
return data;
}
},