【发布时间】:2018-05-28 06:41:10
【问题描述】:
我使用 AJAX 请求从控制器获取结果以将它们填充到数据表中。结果以 JSON 格式从控制器返回,但我不断收到 Uncaught TypeError: Cannot read property 'length' of undefined 错误。
还有我应该在控制器中设置的数据表参数吗?
控制器类:
@RequestMapping(value = "/users/list", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List<User> listOfUsers() {
List<User> usersList;
usersList = userService.getAllUsers();
return usersList;
}
百里香中的数据表用户界面:
<div class="table-responsive">
<table id="usersTable" class="table table-bordered table-hover dataTable">
<thead>
<tr>
<th th:text="#{user.table.heading.username}">User Name</th>
<th th:text="#{systemUser.table.heading.firstname}">First Name</th>
<th th:text="#{systemUser.table.heading.lastname}">Last Name</th>
<th th:text="#{systemUser.table.heading.status}">Status</th>
<th th:text="#{systemUser.table.heading.role}">Role</th>
</tr>
</thead>
</table>
</div>
AJAX 请求:
<script th:inline="javascript">
$(document).ready(function () {
$('#usersTable').DataTable({
"processing": true,
dataType: 'json',
"ajax": {
"url": "http://localhost:8080/sample/users/list",
"type": "GET"
},
"columns": [
{"data": "username"},
{"data": "firstName"},
{"data": "lastName"},
{"data": "status"},
{"data": "roleName"}
]
})
});
</script>
JSON 响应:
[
{
"id":1,
"username":"dinesh@example.com",
"firstName":dinesh,
"lastName":damian,
"password":"$2a$10dfgfdgfdgd6O.iO6XB5xcyEZuppAHWOZGwX8m8xCLqS",
"status":"ACTIVE",
"role":{
"id":1,
"roleName":"ADMIN",
"status":"ACTIVE",
"permissionList":[
{
"id":1,
"name":"ROLE_LOGIN",
"description":"User login permission",
"checked":false
}
],
"checkedPermissions":[
]
}
} ]
【问题讨论】:
-
在您的 json 响应中,您的用户列表必须在
'data'元素中。喜欢'data' = usersList -
那么我怎样才能将 JSON 转换成那种格式呢?
-
在spring mvc中不知道怎么做对不起。
-
1.您的表有 5 行,而 JSON 响应给出 7 - 'id' 和 'password' 丢失。您也应该添加 {"data": "id", bVisible: false} 和另一个。 2. JSON 1st level 没有'roleName',有'role'
标签: spring-mvc datatables thymeleaf