首页 > 解决方案 > 执行@PostMapping 并留在页面上而不进行重定向

问题描述

我使用 Spring Boot。

有一个页面显示所有广告。我需要将广告添加到收藏夹。这必须在不导航到其他页面或重新加载当前页面的情况下完成。因此用户可以单击按钮并进一步滚动,其中已添加到收藏夹。没有重定向怎么办?

我尝试了不同的变体,但它不起作用。请帮帮我!(

我知道我必须使用js,但它对我不起作用。我也需要改变方法addToFavorites。你能改变我的代码并清楚地显示它吗?

我的 HTML:

<div th:each="ad : ${page.getContent()}">
      <div>
        <div>
          <p><a th:href="@{/advert/{id}(id=${ad.getId()})}" th:text="${ad.getHeadline()}">Headline</a></p>
          <p th:text="${ad.getDescription()}">Description</p>
          <p><i class="fa fa-map-marker" aria-hidden="true" th:text="${dao.getLocation(ad)}"></i> New York</p>
          <p><i class="fa fa-clock-o" aria-hidden="true"></i><span th:text="${dao.getDate(ad)}">12.07.2020 19:08</span></p>
        </div>
          <form  th:action="@{/favorites}" method="post">
            <input type="hidden" name="ad" th:value="${ad}">
            <button type="submit">Add to favorites</button>
          </form>
      </div>
    </div>

我的爪哇:

    @GetMapping("/advert")
    public String mainPage(@PageableDefault(sort = {"id"}, size = 10, direction = Sort.Direction.DESC) Pageable pageable,
                           Model model) {
        Page<Advert> page = advertDAO.findAll(pageable);
        model.addAttribute("page", page);
        model.addAttribute("dao", advertDAO);
        return "main";
    }

    @PostMapping("/favorites")
    public void addToFavorites(@RequestParam("ad") Advert advert){
        // add to favorites
    }

标签: javascriptjavahtmlspring-bootspring-mvc

解决方案


要在不重定向的情况下进行 POST 调用,您可以在单击按钮时使用 ajax 调用,该调用将调用您的控制器并给出响应。

$.ajax({
type: "POST", // It can be GET also
url: "your_ulr",
success: function(response){
    //if request if made successfully then the response represent the data
    // Do here whatever you want
   } 
});

推荐阅读