【发布时间】:2021-01-09 02:19:48
【问题描述】:
我使用 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>
我的 Java:
@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
}
【问题讨论】:
-
您需要发送异步(Ajax)请求。请参阅此stackoverflow.com/a/11855073/607637。为此,您将需要 jquery。您可以使用 webjars 安装它。 webjar的使用方法见github.com/gtiwari333/spring-boot-web-application-seed/blob/…
-
@gtiwari333 jQuery 正在衰落,尤其是在引入the Fetch API 之后。
-
@chrylis-cautiouslyoptimistic- 是的.. 如果我们能用 vanilla js 做到这一点,那就太好了。使用 jquery 大约 12 年。我认为它仍然很棒:)
-
@gtiwari333 我应该在方法
addToFavorites()中更改什么? -
I know that I have to use js, but it doesn't work for me这是什么意思?你已经尝试过使用 JS 了吗?如果是这样,你能分享你的尝试吗?
标签: javascript java html spring-boot spring-mvc