【问题标题】:GET method sent instead of DELETE发送 GET 方法而不是 DELETE
【发布时间】:2019-06-03 18:48:24
【问题描述】:

我正在尝试编写应用程序的前端,但遇到了问题。我一直在尝试使用 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:/";
  }

我该如何解决这个问题?提前谢谢你。

【问题讨论】:

标签: java html ajax spring thymeleaf


【解决方案1】:

您花了很长的时间解决这个问题。

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

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

event.preventDefault()

而不是:

xhttp.preventDefault()

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

【讨论】:

    【解决方案2】:

    在一些帮助下,我可以找出问题所在。基本问题是
    标签只能处理 GET 方法。

    而不是我的那部分代码,我在 HTML 中这样整理出来:

        <td>
            <form th:method="DELETE" th:action="|/delete/*{id}|">
                <input type="submit" value="Send">
            </form>
        </td>
    

    现在可以完美运行了。

    【讨论】:

    • 我认为你已经走了很长一段路。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2021-08-03
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多