spring-mvc - 未捕获的类型错误:无法读取未定义 spring+thymeleaf+datatables 的属性“长度”
问题描述
我使用 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":"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":[
]
}
}]
解决方案
通常无法读取未定义的属性“长度”意味着 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
更多信息,请参阅。
推荐阅读
- button - Flutter:其他应用程序前面的浮动按钮
- javascript - 不知道为什么我会返回一个 NaN - 在 fn() 内部它有效 - 在外部它没有
- powershell - PowerShell 脚本将 SQL 导出到 CSV 添加分隔符
- c# - GetAllUsers 问题,忽略从属 OU
- javascript - 如何获取特定级别 DOM 的 div id?
- jackson - 在 Avro Schema 中使用 Map 对字段进行排序
- c++ - 使用 STL 算法在表(向量的向量、二维数组)中查找最小值/最大值的优雅方法
- julia - 嵌套追加到 Julia 中的数组
- android-fragments - 毕加索图像不显示在圆形视图中
- javascript - SAPUI5 增强后访问错误的 i18n 文件