How to populate rows of jQuery datatable with JSON object sent back from Spring MVC?
Solution 1
Example from the datatable site gives you all the details required.
Example JS code
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/server_processing.php" // for you it will be - /getWidgetsByType
} );
} );
Your json should be something like this
{
"sEcho": 1,
"iTotalRecords": "57",
"iTotalDisplayRecords": "57",
"aaData": [
[],[],[],...
]
}
Here's example showing to set the column names on the fly.
Cheers!!
Solution 2
1.Controller
@RequestMapping(value = "/json", method = RequestMethod.GET)
public
@ResponseBody
String listUsersJson(ModelMap model) throws JSONException {
int no=1;
JSONArray userArray = new JSONArray();
for (TileType tT: tD.getAll()){
String n=Integer.toString(no);
String id=Integer.toString(tT.getTileTypeId());
String[] value =
{n,
tT.getTileTypeName(),
tT.getTileTypeDensity()
};
userArray.put(value);
no++;
}
String x=userArray.toString();
String replace1=x.replace("{", "[");
String replace2=replace1.replace("}","]");
String replace3=replace2.replace(":",",");
return ("{\"aaData\":"+replace3+"}");
}
2.Dao
@Override
public List<TileType> getAll() {
Session session=HibernateUtil.getSessionFactory().openSession();
List<TileType>list=new ArrayList<TileType>();
try{
Query query=session.createQuery("from TileType T order by T.tileTypeId DESC");
list=query.list();
}
catch(HibernateException he){}
return list;
}
3.Javascript
var table = $('#example').dataTable({
"sPaginationType": "full_numbers",
"sAjaxSource": "/data/tipeTile/json",
"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"sSearch": ""
}
});
4.Html
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
<thead>
<tr>
<th style="width: 50px">No</th>
<th>Name</th>
<th>Density</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Hope this Help
Solution 3
The easiest way to get the appropriate JSON data from Spring to DataTable is that instead of returning a list of your entity, return a map like this:
@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST)
public @ResponseBody Map<String, WidgetVO> getWidgetsByType(@RequestParam("type") String type) {
Map<String, WidgetVO> result = new HashMap<>();
result.put("WidgetVO", widgetDAO.getWidgetsByType(token));
return result;
}
That's it and now you can have access to your objects:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "data/objects.txt",
"dataSrc": "WidgetVO",
"columns": [
{ "data": "type" },
{ "data": "name" },
{ "data": "isAwesome" }
]
});
});
IAmYourFaja
my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.
Updated on June 08, 2022Comments
-
IAmYourFaja almost 2 years
I have a Java (Spring MVC) backend that returns POJOs as JSON objects as follows:
@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST) public @ResponseBody List<WidgetVO> getWidgetsByType(@RequestParam("type") String type) { return widgetDAO.getWidgetsByType(token); } public class WidgetVO { private String type; private String name; private boolean isAwesome; // Getters and setters, etc. }
In the frontend I'm trying to call
/getWidgetsByType
from inside a jQuery$.getJSON
call, and then use the JSON results coming back from that to populate a datatable. Specifically, I want the datatable to appear inside a<div>
tag that is currently empty at page load as follows:<div id="#table-to-display"></div> var t = getTypeFromDOM(); $.getJSON( url: "/getWidgetsByType", data: { type: t }, success: function() { // How do I extract the JSON version of the List<WidgetVO>'s coming // back from the server and use them to populate the table? $("#table-to-display").datatable(); } );
I would like the
datatable
to contain the same columns as the fields of theWidgetVO
(type, name, isAwesome), all asString
values (no renderers, etc.).Thanks in advance for any help here!
-
IAmYourFaja over 11 yearsThanks @bhb (+1) - but are
bProcessing
andbServerSide
datatable params or app-specific query string params? What if my server-side is not a PHP file but a Spring MVC handler that gets mapped from the URL/getWidgetsByType
? Thanks again! -
bhb over 11 years
-
IAmYourFaja over 11 yearsSo do I even need to call
$.getJSON
, or does the$("#table-to-display").datatable() { ... };
call do it for me? -
bhb over 11 yearsNo probs :). So if the json is an array of array like
{demo:[[],[]...]}
, then the order of the array elements specifies the column order. -
bhb over 11 yearsdatatable does it for you... no need to call
$.getJSON
. -
IAmYourFaja over 11 yearsThat's so cool. Thanks again - all the lightbulbs (well, most of them) just went on. thanks for helping me connect the dots
-
Navdeep Singh almost 11 yearsHi Everyone, Can anyone please validate my json string: { "iTotalRecords": 20, "iTotalDisplayRecords": 5, "aaData": [ { "name": "Sandeep1", "mark": "201" }, { "name": "Sandeep2", "mark": "202" }, ] }