[英]Spring MVC + jQuery Datatables + JSON Response
我有一个使用jQuery Datatables的Spring MVC应用程序来呈现数据。 这是我的课程和JavaScript代码
Employee.java
public class Employee {
private int empId ;
private String firstName;
private String lastName ;
// getters and setters
}
EmployeeResponse.java
public class EmployeeResponse {
private List<Employee> empList ;
// getters and setters
}
EmployeeController.java
@Controller
@RequestMapping("/admin")
public class EmployeeController {
@RequestMapping(value = "/get-all-employee", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public EmployeeResponse getAllEmployee(HttpServletRequest request) {
EmployeeResponse response = new EmployeeResponse();
try {
response = getAllEmployeeList(); // returns response object
} catch (Exception e) {
logger.error("DCConsoleController::createNewStream exception: " + com.priceline.utils.StringUtils.getStackTrace(e));
return null;
}
return response ;
}
}
emp.jsp
<div class="row">
<table id="ldapStreamTable" class="table">
<thead>
<tr>
<th>Emp Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
</table>
</div>
emp.js
$(document).ready(function() {
var table = $('#appTable').DataTable( {
"sDom" : domSetting,
"oLanguage" : {
"sLengthMenu" : "_MENU_ records per page",
"sSearch" : "<span class='add-on'><i class='icon-search'></i></span>Search Application:",
"sZeroRecords" : "No matching records found",
},
"iDisplayLength" : 10,
"aLengthMenu" : [
[ 5, 10, 20, 25, 50, -1 ],
[ 5, 10, 20, 25, 50, "All" ] ],
"aaSorting" : [ [ 0, 'asc' ] ],
'sAjaxSource': '{context}/admin/get-all-employee',
[Pending here]
});
});
我应该怎么做才能将响应作为json并为每列应用/使用render方法将数据呈现到表中?
[注意:看起来我不能对每列使用带有mData的aoColumns'因为我的json响应是员工对象列表]
更新 - 1:下面的示例json
{"empList":[{"empId":3,"firstName":"Kiran","lastName":"Kumar"},{"empId":1,"firstName":"John","lastName":"Smith"},{"empId":0,"firstName":"Sachin","lastName":"Kumar"}]}
我已经将你的样本ajax
数据保存在github
并将其作为ajax
源提供。 你将那个部分保留在返回json
响应的method
中,但是在json
响应中不是empList
作为基本根,而是将其替换为我在上面的github
json
文件中所做的data
。 现在除了ajaxSource
之外,您需要将columns
映射到您的dataTables
,如下所示:
"columns": [
{ "data": "empId"},//should match column value in json file
{ "data": "firstName"},//should match column value in json file
{ "data": "lastName"}//should match column value in json file
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.