javascript - 执行@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
}
解决方案
要在不重定向的情况下进行 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
}
});
推荐阅读
- firebase - 类'列表
' 在 Flutter 中没有实例方法 'call' - html - 更改 img 标签的颜色
- gitlab - 在权限中看不到 Gitlab 包功能
- postgresql - Postgres 获取具有逗号分隔值的列表
- kubernetes - 我需要打开哪个端口以允许 pip 连接(在通过 kubernetes 运行的 docker 中)?
- python - 将一系列数组转换为单个列表
- c++ - OpenCL:实现查找表
- php - 如何在 AWS Linux / CentOS 上使用 Yum 更新 PHP 版本
- python - 如何使用python从mysql数据库的信息中执行用户输入
- python - 32 位 pyodbc 和 32 位 Python 是否可以与 64 位 MS 访问数据库通信?