我正在尝试使用ajax在屏幕上显示用户列表。然而,我只得到一个对象。就是ftlh文件里的数据因为某种原因没有来。求助,为什么会出现这种情况?以及如何解决问题。
这是控制器的代码:
@GetMapping("/users")
public ResponseEntity<?> getAllUsers() {
List<User> userList = service.getAllUsers();
List<UserResponse> users = new ArrayList<>();
userList.forEach(user->
users.add(new UserResponse(user.getUuid(),
user.getUsername(),
user.getEmail(),
user.getRole(),
user.getBalance(),
user.getState()))
);
return ResponseEntity.ok(users);
}
这是 freemarker 的代码:
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h1>User List</h1>
<table id="user-table" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
$(document).ready(function() {
$.ajax({
url: "/users",
type: "GET",
dataType: "json",
success: function(users) {
users.forEach(function(user) {
let row = $("<tr>" +
"<td>" + user.uuid + "</td>" +
"<td>" + user.username + "</td>" +
"<td>" + user.email + "</td>" +
"</tr>");
$("#user-table tbody").append(row);
});
}
});
});
</script>
</body>
</html>
我尝试将@RestController更改为@Controller,返回字符串,返回方法本身,但没有任何帮助。请帮我解决问题
我复制了它并运行它,没有太多问题,我只需确保
UserResponse
具有适当的吸气剂,以便序列化能够工作。显然,您可以访问 /users
来检查您是否收到了 JSON。
我怀疑您出错的地方是数据中存在某些内容,因此您构建行的简单连接会创建无效的 HTML。 试试这个:
let row = $("<tr>").append(
$('<td>').text(user.uuid),
$('<td>').text(user.username),
$('<td>').text(user.email)
);