【发布时间】:2019-06-01 05:30:57
【问题描述】:
我正在开发一个 Spring Boot 应用程序。我有一个收藏按钮,其中按钮图像会根据用户是否收藏该项目而改变。
最初我通过接受表单发布请求、更新数据库并将重定向发送回Referer来使其工作,但这每次都会重新加载页面,所以我想我会尝试使用jQuery Ajax。
Controller.java:
// //Favorite/Unfavorite existing recipes
// @RequestMapping(value = "/recipes/{id}/favorite", method = RequestMethod.POST)
// public String favoriteRecipe(@PathVariable Long id, Model model, HttpServletRequest request, Authentication
// authentication) {
//
// User user = userService.findByUsername(authentication.getName());
// model.addAttribute("user", user);
// Recipe recipe = recipeService.findById(id);
//
// userService.toggleFavorite(user, recipe);
//
// userService.save(user);
//
// return "redirect:" + request.getHeader("Referer");
// }
// Favorite/Unfavorite existing recipes
@PostMapping("/recipes/{id}/favorite")
@ResponseStatus(value = HttpStatus.OK)
public void favoriteRecipe(@PathVariable("id") Long id, Model model, Authentication authentication) {
User user = userService.findByUsername(authentication.getName());
//model.addAttribute("user", user);
Recipe recipe = recipeService.findById(id);
userService.toggleFavorite(user, recipe);
userService.save(user);
//return new ResponseEntity<>(HttpStatus.OK);
}
index.html:
<a th:href="@{|/details/${recipe.id}|}">
<div class="grid-70">
<p>
<form id="test" th:action="@{|/recipes/${recipe.id}/favorite|}" method="post" style="display:inline">
<button type="submit" id="favorite-button-index">
<img th:src="${recipe.userFavorites.contains(#authentication.name)} ? @{/assets/images/favorited.svg} : @{/assets/images/favorite.svg}"
style="height: 12px;">
</button>
</form>
<span th:text="${recipe.name}"> </span>
</p>
</div>
</a>
app.js:
$('#test').submit(function (e) {
e.preventDefault()
$('#favorite-button-detail').submit(function (e) {
e.preventDefault()
var recipeID = [[${recipe.id}]];
var url = "/recipes/" + recipeID + "/favorite";
$.post(url, function(data) {
alert(data)
});
})
})
这是我尝试在我的 app.js 中实现的方式。我已经确认数据库中的数据正在更新,但我无法停止重定向到 POST url。问题似乎来自表单中的 th:action。
我已经查看了很多其他问题/示例,但无法弄清楚为什么会发生这种情况。我尝试过 preventdefault,返回 false,包装在 $( document ).ready() 中。
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
哇哇哇哇,你在
.submit()里面有.submit()。内部的根本不需要 -
当有人点击您的提交按钮时,它会提交您的表单。所以你不需要
$('#favorite-button-detail').submit
标签: javascript java jquery spring-boot