I was trying to add the DataTable in my application. https://datatables.net/ I have a WebPage in which data table to be shown on onclick event, when system trigger onclick event ajax call get made and data will come from the Java servlet. below is my code
JSP:
<table id="testTable" class="display" cellspacing="0"
width="100%" cellpadding="0" border="0">
<thead>
<tr>
<th>Test</th>
<th>Description</th>
<th>Result</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
</table>
JQuery:
function getTestData(name, e, bId) {
$('#testTable').dataTable( {
"serverSide": true,
"processing": true,
"ajax":{
"type" : "POST",
"dataSrc": "data",
"url" : "Servlet",
"dataType": "json",
"data" : {
name : name,
e : e,
bId : bId,
method : "getTestData"
},
"sEcho": 0,
"processing": true,
"columns":[
{ "data": "tId" },
{ "data": "description" },
{ "data": "rst" },
{ "data": "startDate" },
{ "data": "endDate" }
]
}
} );
}
Servlet is returning below JSON:
{
"data": [
{
"tId": "1",
"description": "desc",
"rst": "P",
"startDate": "2016-09-13 07:59:31.0",
"endDate": "2016-09-13 07:59:51.0"
},
{
"tId": "2",
"description": "desc",
"rst": "S",
"startDate": "2016-09-13 07:59:51.0",
"endDate": "2016-09-13 07:59:51.0"
}
]
}
I am getting below error :
DataTables warning: table id=testTable - Requested unknown parameter '0' for row 0, column 0.
I know the reason of error but not sure what i am doing wrong in the above code, I guess something wrong in the jquery code. Please help.
Thanks in advance
The JSON should be in below mentioned format
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
[
"Angelica",
"Ramos",
"Chief Executive Officer (CEO)",
"London",
"9th Oct 09",
"$1,200,000"
]
]
}
https://datatables.net/examples/data_sources/server_side.html
Change your initialization code to match your JSON data format as shown below.
$('#testTable').dataTable({
"ajax": {
"type": "POST",
"url": "Servlet"
},
"columns": [
{ "data": "tId" },
{ "data": "description"},
{ "data": "rst" },
{ "data": "startDate" },
{ "data": "endDate"}
]
});
See this jsFiddle for code and demonstration.
The way you initializing the datatable is not correct, can look here for different ways to do it.
@Gyrocode.com's answer picks up from what you probably struggling on. Am just giving you one more answer, am thinking maybe can consider getting the data and passing it to your data table
$.getJSON("http://example/servlet_data.json", function(fromServer) {
$('#testTable').DataTable( {
data: fromServer.data,
columns: [
{ data: "tId" },
{ data: "description"},
{ data: "rst"},
{ data: "startDate"},
{ data: "endDate"}
]
} );
}).fail(function(){
alert("Error occurred getting data from the server");
})
Happy coding
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.