首页 > 解决方案 > 未捕获的类型错误:无法读取未定义 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":[  

     ]
  }

}]

标签: spring-mvcdatatablesthymeleaf

解决方案


通常无法读取未定义的属性“长度”意味着 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更多信息,请参阅。


推荐阅读