Spring Boot无法从JQuery接收POST

时间:2018-08-12 15:18:17

标签: jquery spring-boot

我想将一些数据发布到后端,所以我使用了jQuery:

<section>
    <script>    
        $("#score").click(function () {
            var usual = $(".usual").val();
            var final = $(".final").val();
            var total = $(".total").val();
            var student = $("#student").text();
            $.post("/teacher/students/score",{"student":student,"usual":usual,"final":final,"total":total},function(data){
                alert(data);
            });
        })
    </script>
</section> 

我写了一个控制器:

@PostMapping("/teacher/students/score")
public void score(@RequestParam(name = "id") String student,
                  @RequestParam(name = "usual") int usualScore,
                  @RequestParam(name = "final") int finalScore,
                  @RequestParam(name = "total") int totalScore,
                  HttpSession session,
                  HttpServletResponse response){

    //process data...
}

但是,当我单击页面中的按钮时,后端没有任何反应。似乎控制器无法从jQuery接收POST请求。有人可以帮忙吗?
------------------------更新------------------------- -
我使用Chrome的开发人员工具,然后发现状态码为400。也许这是实际原因?

1 个答案:

答案 0 :(得分:0)

在控制器中,Post方法期望required query parameter,但是您从jquery传递了请求正文。如果要在jquery的post方法中指定查询参数,请使用jQuery.param

尝试一下:

$.post(url: "/teacher/students/score",
       data: jQuery.param({"student":student,"usual":usual,"final":final,"total":total},function(data){
                    alert(data);
                });