【问题标题】:Pass value to controller via AJAX without any user input using Thymeleaf通过 AJAX 将值传递给控制器​​,无需使用 Thymeleaf 进行任何用户输入
【发布时间】:2019-10-02 08:13:07
【问题描述】:

我想创建一个可以删除用户的按钮。我想通过 AJAX 将用户 ID 从 Thymeleaf 发送到我的 Spring MVC 控制器,而无需任何用户输入。

但是,我看到的所有示例都使用表单和表单数据。就我而言,我想在不使用表单的情况下发送我已经从 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>

【问题讨论】:

    标签: javascript ajax spring-mvc thymeleaf


    【解决方案1】:

    将用户 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() {
            ...
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      相关资源
      最近更新 更多