首页 > 解决方案 > 发送 GET 方法而不是 DELETE

问题描述

我正在尝试编写应用程序的前端,但遇到了问题。我一直在尝试使用 AJAX 实现 DELETE 方法,但是根据 Spring,当我运行代码时会发送 GET 。

HTML 代码:

    <tr th:each="attraction : ${attractions}" th:object="${attraction}">
    <td th:text="*{name}"></td>
    <td th:text="*{latitude}"></td>
    <td th:text="*{city}"></td>
    <td><a th:href="|/edit/*{id}|">EDIT</a></td>
    <script>
        function sendDelete(event) {
            xhttp.preventDefault();
            xhttp.open("DELETE", this.href);
            xhttp.send();
        }
    </script>
    <td><a th:href="|/delete/*{id}|" onclick="sendDelete(event);">DELETE</a></td>
</tr>

弹簧代码:

  @DeleteMapping("/delete/{id}")
  String delete(@ModelAttribute Attraction attraction) {
   attractionService.delete(attraction);
   return "redirect:/";
  }

我该如何解决这个问题?先感谢您。

标签: javahtmlajaxspringthymeleaf

解决方案


你走了很长的路来解决这个问题。

链接标签可以发送任何你想要的 http 方法,只要你在 JavaScript 中处理它并且你调用了 preventDefault。

但是您必须对传递给单击处理程序的事件而不是在 xhttp pbject 上执行此操作。所以在你的事件处理程序上你应该做

event.preventDefault()

并不是:

xhttp.preventDefault()

您的表单破解不是惯用的。它会吓坏下一个处理该代码的人!


推荐阅读