【问题标题】:Form Preventdefault not working, redirecting to post urlForm Preventdefault 不起作用,重定向到发布网址
【发布时间】: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


【解决方案1】:

有两个嵌套提交是不好的。而且我不确定在双数组中包装 [[${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 的东西了。

【讨论】:

  • 非常感谢,这解决了我的重定向问题。另外,我不小心输入了双数组哈哈。
【解决方案2】:

除了Roko's 的回答,您还必须想出一个解决方案来刷新您的用户界面,以便在不刷新整个页面的情况下更改按钮图像,因为您使用的是服务器端渲染模板引擎。 我建议您在成功响应后更改按钮的图像,如下所示:

$('#test').on("submit", function (e) {
    e.preventDefault();
    $.post(this.action, function(data) {
        console.log(data);
        var imageUrl = (data.favorited)?'/assets/images/favorited.svg':'/assets/images/favorite.svg'; 
        $('#favorite-button-index>img').attr('src', imageUrl);
    });
};

同样在这种情况下,要使data.favorited 工作,您应该从您的弹簧控制器方法返回有关用户是否喜欢的数据。这是一个返回 json 数据的示例,因此您可以轻松地在 javascript 中使用:

@PostMapping("/recipes/{id}/favorite")
@ResponseBody
public Map<String, Object> favoriteRecipe(@PathVariable("id") Long id, Authentication authentication) {
    User user = userService.findByUsername(authentication.getName());

    Recipe recipe = recipeService.findById(id);
    userService.toggleFavorite(user, recipe);

    userService.save(user);

    boolean hasFavorite = recipe.userFavorites.contains(authentication.getName());

    Map<String, Object> resultJson = new HashMap<>();
    resultJson.put("favorited", hasFavorite);

    return resultJson;
}

【讨论】:

  • 非常感谢您的后续回复。这将是我的下一个挑战。这对于我应该如何解决这个问题非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多