【问题标题】:submit star-rating without redirection in thymeleaf and spring boot, using jquery, ajax使用 jquery、ajax 在 thymeleaf 和 spring boot 中提交星级而不进行重定向
【发布时间】:2020-08-12 17:09:33
【问题描述】:

我在我的项目中使用星级评价 jquery 插件,这里是链接https://plugins.krajee.com/star-rating#implementations。所以,点击星星后,我想在没有重定向的情况下提交结果,在 og ajax 的帮助下,但我得到了像 Post http://localhost/rating/56 (id of project) 404 not found 这样的错误 这是我的代码

<form th:action="@{/rating/{id}(id=${projects.id})}" th:object="${rating}" method="post">
  <input  value="0" th:field="*{stars}"   hidden class="rating" data-glyphicon="0"
                                               id="stars">
</form>

ajax 代码在这里

 $(document).ready(function() {
        var id=/*[[${projects.id}]]*/
        $('#stars').on('rating.change', function(event, value) {
            event.preventDefault();
            $.ajax({
                type: "post",
                contentType: "application/json",
                url: "/rating/" + id,
                data : JSON.stringify(id),
                dataType : 'json',
                dataType: 'json',
                success: function () {
                    console.log(id)
                }
            })
        });
    });

这是我的弹簧控制器

  @RequestMapping(value = "/rating", method = RequestMethod.POST)
@ResponseBody
public String rating(@RequestParam(value = "id") Long id, Model model, RatingModel ratingModel){
    try {
        projectService.save(ratingModel,  id);
    } catch (Exception e) {
        log.error("You have already rated");
    }
    return "redirect:/project/show-project/" + id;

}

据我所知,在春季我应该使用@RestController 来调用 ajax,但不是那样,而是在这里我用@RequestParams 添加了@ResponseBody 注释,但我很困惑为什么这个实现不起作用

请帮忙

【问题讨论】:

    标签: javascript jquery ajax spring-boot thymeleaf


    【解决方案1】:

    花了一个小时解决一个问题后,我明白问题出在 spring security 中,我的意思是,我补充说 http.csrf().ignoringAntMatchers("/rating/**"). 在我的 SecurityConfig 类中,我的 ajax 工作,希望它对遇到同样问题的人有所帮助

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2018-01-03
      • 2023-03-29
      • 2021-09-16
      • 2019-07-22
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多