表单Preventdefault无效,重定向到发布网址

我正在开发一个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);

    }


这是我尝试在我的app.js中实现的方式。我已经确认数据库中的数据正在更新,但是我无法停止重定向到POST URL。问题似乎来自表单中的th:action。


我已经查看了很多其他问题/示例,但仍无法弄清楚为什么会发生这种情况。我尝试了preventdefault,返回false,包装在$(document).ready()中。


任何帮助将不胜感激。谢谢!


阿波罗的战车
浏览 136回答 2
2回答

GCT1015

除了Roko的答案,您还必须想出一种解决方案来刷新ui,以便在不刷新整个页面的情况下更改按钮图像,因为您使用的是服务器端渲染模板引擎。我建议您在成功响应后,只需更改按钮的图像,如下所示:$('#test').on("submit", function (e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; $.post(this.action, function(data) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; &nbsp; var imageUrl = (data.favorited)?'/assets/images/favorited.svg':'/assets/images/favorite.svg';&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $('#favorite-button-index>img').attr('src', imageUrl);&nbsp; &nbsp; });};同样在这种情况下,为了data.favorited工作,您应该从spring控制器方法返回有关用户是否喜欢的数据。这是一个返回json数据的示例,因此您可以轻松地在javascript中使用它:@PostMapping("/recipes/{id}/favorite")@ResponseBodypublic Map<String, Object> favoriteRecipe(@PathVariable("id") Long id, Authentication authentication) {&nbsp; &nbsp; User user = userService.findByUsername(authentication.getName());&nbsp; &nbsp; Recipe recipe = recipeService.findById(id);&nbsp; &nbsp; userService.toggleFavorite(user, recipe);&nbsp; &nbsp; userService.save(user);&nbsp; &nbsp; boolean hasFavorite = recipe.userFavorites.contains(authentication.getName());&nbsp; &nbsp; Map<String, Object> resultJson = new HashMap<>();&nbsp; &nbsp; resultJson.put("favorited", hasFavorite);&nbsp; &nbsp; return resultJson;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java