我有一个 Java (Spring MVC) 后端,它返回 POJO 作为 JSON 对象,如下所示:
@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.
}
在前端,我试图调用 /getWidgetsByType
来自 jQuery $.getJSON
调用,然后使用返回的 JSON 结果来填充 datatable .具体来说,我希望数据表出现在 <div>
中。页面加载时当前为空的标记如下:
<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();
}
);
我想要 datatable
包含与 WidgetVO
的字段相同的列 (类型、名称、isAwesome),全部为 String
值(无渲染器等)。
在此先感谢您的帮助!
最佳答案
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.道
@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>
希望对你有帮助
关于java - 如何使用从 Spring MVC 发回的 JSON 对象填充 jQuery 数据表的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841510/