javascript - 使用 Thymeleaf 将值通过 AJAX 传递给 Controller ​​,无需任何用户输入

标签 javascript ajax spring-mvc thymeleaf

我想创建一个可以删除用户的按钮。我想通过 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/

相关文章:

javascript - 从函数-Node JS -socket.io发出事件的正确方法

php - 使用 JQuery 在 PHP 文件中加载内容

javascript - 在 while 循环中使用 if 语句

javascript - React-admin:使用文档中显示的自定义登录页面时出错

c# - ASP.NET Core 模型未通过 AJAX 绑定(bind)到 Controller

php - 通过 AJAX 将两个 JSON 模型对象从 PHP 传递到 JS

javascript - 文档 execCommand 副本不适用于 AJAX

spring - 在 Spring Controller 中,我可以根据请求参数的数量调用方法吗?

angularjs - 隐藏/显示 AngularJS 或基于经过身份验证的用户权限的任何其他单页应用程序 ui 组件的正确方法是什么?

Spring Boot启动监听器