I'm trying load json data on table using datatables
The return of json from php is like this:
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
}
In the documentation columns data they say that I need to follow this structure:
table.DataTable({
"ajax": url,
columns: [
{"data": "CLIENTES.ID"},
{"data": "CLIENTES.NOME"}
]
});
But dont work, and we know that the right acess to de data index is this way:
{"data": "CLIENTES['0'].ID"},
{"data": "CLIENTES['1'].ID"},
But need's to be dynamically, how can I do this?
You should create new data for datatable without CLIENTES
.... map is an option.
$(document).ready(function() {
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
};
var newData = $.map(data.CLIENTES, function(el) { return el });
$('#example').DataTable({
data: newData,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});
});
If you remove the 'CLIENTES' outer array and only return an array of the results in your PHP, you will be able to refer to the values like this:
table.DataTable({
"ajax": url,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});
you can do things to an object dynamically by using for var in
var myArray = [] //an empty array
for(var i in data){
myData.push({"data": "CLIENTES[i].ID"})
myData.push({"data": "CLIENTES[i].NOME"})
}
then later you can do this
table.DataTable({
"ajax": url,
columns: myArray
});
but I suspect the way you write {"data": "CLIENTES[i].ID"}
is wrong, though i havent used datatables
before.
maybe something like this is more correct? it's how you usually get to object properties
for(var i in data){
myData.push({"data": data.CLIENTES[i].ID})
myData.push({"data": data.CLIENTES[i].NOME})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.