如何使用从Spring MVC发回的JSON对象填充jQuery数据行的行?
我有一个Java (Spring MVC)后端,它将POJO作为JSON对象返回如下:
@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST) public @ResponseBody List 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. }
在前端我试图从jQuery $.getJSON
调用中调用/getWidgetsByType
,然后使用从中返回的JSON结果来填充数据表。 具体来说,我希望数据表出现在页面加载时当前为空的
标记内,如下所示:
var t = getTypeFromDOM(); $.getJSON( url: "/getWidgetsByType", data: { type: t }, success: function() { // How do I extract the JSON version of the List's coming // back from the server and use them to populate the table? $("#table-to-display").datatable(); } );
我希望数据表包含与WidgetVO
(type,name,isAwesome)的字段相同的列 ,所有列都是String
值(没有渲染器等)。
在此先感谢您的帮助!
数据表站点中的示例为您提供了所需的所有详细信息。
示例JS代码
$(document).ready(function() { $('#example').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "scripts/server_processing.php" // for you it will be - /getWidgetsByType } ); } );
你的json应该是这样的
{ "sEcho": 1, "iTotalRecords": "57", "iTotalDisplayRecords": "57", "aaData": [ [],[],[],... ] }
这是一个示例,显示了动态设置列名称。
干杯!!
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 getAll() { Session session=HibernateUtil.getSessionFactory().openSession(); List list=new ArrayList (); 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
No Name Density
希望这个帮助
从Spring到DataTable获取适当的JSON数据的最简单方法是,不是返回实体列表,而是返回如下地图:
@RequestMapping(value = "/getWidgetsByType", method = RequestMethod.POST) public @ResponseBody Map getWidgetsByType(@RequestParam("type") String type) { Map result = new HashMap<>(); result.put("WidgetVO", widgetDAO.getWidgetsByType(token)); return result; }
就是这样,现在您可以访问您的对象:
$(document).ready(function() { $('#example').dataTable( { "ajax": "data/objects.txt", "dataSrc": "WidgetVO", "columns": [ { "data": "type" }, { "data": "name" }, { "data": "isAwesome" } ] });
});