我正在开发 Spring Boot 应用程序。我有一个最喜欢的按钮,其中按钮图像会根据用户是否 Collection 了该项目而变化。
最初我通过接受表单发布请求、更新数据库并将重定向发送回 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>
应用程序.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() 中。
如有任何帮助,我们将不胜感激。谢谢!
最佳答案
有两个嵌套提交是不好的。而且我不确定将 [[${recipe.id}]]
包装成双数组背后的想法是什么......??
尝试:
$('#test').on("submit", function (e) {
e.preventDefault();
$.post(this.action, function(data) {
console.log(data);
});
});
其中 this.action
是实际表单的 action 属性值 @{|/recipes/${recipe.id}/favorite|}
而且您不再需要任何按钮 JS 东西。
关于javascript - Form Preventdefault 不起作用,重定向到发布 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54059343/