我想创建一个可以删除用户的按钮。我想通过 AJAX 将用户 ID 从 Thymeleaf 发送到我的 Spring MVC Controller ,而不需要任何用户输入。
但是我见过的所有示例都使用表单和表单数据。就我而言,我想发送我已经从 Thymeleaf 获得的数据,而不使用表单。我怎样才能做到这一点?
<tr th:each="user : ${userList}">
<th scope="row"><span th:text="${user.id}"></span></th>
<td><span th:text="${user.username}"></span></td>
<td><span th:text="${user.email}"></span></td>
<td width="60">
<div class="dropdown">
<button class="btn btn-light btn-block dropdown-toggle text-right" type="button" data-toggle="dropdown"><span th:text="${user.roles[0].role}"></span>
<span class="caret"></span></button>
<ul class="dropdown-menu">
<div th:each="role : ${user.roles}">
<span th:href="@{'/users/manageRole' + ${user.id}}" th:text="${role.role}"></span>
</div>
</ul>
</div>
</td>
<td>
I want to send ${user.id} as a DELETE method to /admin/users from Thymeleaf here
My attempt without AJAX using URL parameter :
<form method="DELETE" th:action="@{'/admin/users/' + ${user.id}}"
<button type="submit" class="btn btn-light btn-block" id="submit">Delete User</button>
</form>
Problem with this implementation is the button redirects to /admin/users/${user.id},
I don't want any redirects. I also would prefer not to show the user ID as a parameter in the URL.
</td>
最佳答案
将用户 ID 存储在隐藏输入(或任何其他 html 元素)中:
<input id="userIdInput" th:value="${user.id}" hidden>
然后在 js 中检索它并进行您需要的 ajax 调用(假设您正在使用 JQuery 的示例;将其放入函数中并在单击按钮或任何适合您需要的操作时调用它):
$.ajax({
url : '...',
type : 'POST',
data : $("#userIdInput").val(),
cache : false,
contentType : false,
processData : false,
success : function(returndata) {
...
},
error : function() {
...
}
});
关于javascript - 使用 Thymeleaf 将值通过 AJAX 传递给 Controller ,无需任何用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197626/