未捕获的类型错误:无法读取未定义的 spring+thymeleaf+datatables 的属性“长度”
2018-05-28
479
我使用 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;
}
thymeleaf 中的数据表 UI:
<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":"[email protected]",
"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":[
]
}
} ]
2个回答
通常 无法读取未定义的属性‘length’ 意味着DataTables无法在响应中找到数据。
使用以下初始化选项来匹配您的响应结构。
$('#usersTable').DataTable({
"processing": true,
dataType: 'json',
"ajax": {
"url": "http://localhost:8080/sample/users/list",
"type": "GET",
"dataSrc": ""
},
"columns": [
{"data": "username"},
{"data": "firstName"},
{"data": "lastName"},
{"data": "status"},
{"data": "role.roleName"}
]
});
有关更多信息,请参阅
ajax.dataSrc
。
Gyrocode.com
2018-05-30
将 AJAX 请求改成这样后,渲染成功。
<script th:inline="javascript">
$(document).ready(function () {
$('#usersTable').DataTable({
"sAjaxSource": "http://localhost:8080/sample/users/list",
"sAjaxDataProp": "",
"aoColumns": [
{"mData": "username"},
{"mData": "firstName"},
{"mData": "lastName"},
{"mData": "status"},
{"mData": "role.roleName"}
]
})
});
<script th:inline="javascript">
GeekySelene
2018-06-20