春季启动应用程序中的ajax POST请求

时间:2017-01-04 22:50:10

标签: jquery ajax spring

我正在尝试在没有导航或刷新页面的情况下在服务器上执行操作。据我所知,我需要使用AJAX调用。 我尝试了两种方法,但遇到了问题。

控制器版本1:

@RequestMapping(value = "/vote", params = {"match","player", "voteValue"}, method  = RequestMethod.POST)

                public  @ResponseBody String voteup(@RequestParam("match") int match, @RequestParam("player") int player,  @RequestParam("voteValue") int voteValue){

                voteService.save(match, player, voteValue);
                String returnText = "Vote has been recorded to the list";
                return returnText;

                }

控制器版本2:

@RequestMapping(value = "/vote", method  = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public  String voteup( @RequestBody Vote vote  ){
        vote.getMatch();

                //voteService.save(match, player, voteValue);
            String returnText = "Vote has been recorded to the list";
            return returnText;
    }   

JSP:

<c:if test = "${not empty matchform.lineup }">
                                 <c:forEach var="lineup" items="${matchform.lineup}">

                                    <c:if test = "${lineup.team.apiTeamId eq matchform.homeTeam.apiTeamId}">
                                    <hr>${lineup.player_name}  -  ${lineup.position}
                                          <form action="/vote" method=post  id = vote-form> 
                                                <button class="btn btn-xs btn-primary btn-block" type="submit" >Vote Up</button> 
                                                <input type="hidden" id = match name="match" value="${lineup.matchId.id}" />
                                                <input type="hidden" id = player name="player" value="${lineup.player.id}" />
                                                <input type="hidden" id = voteValue name="voteValue" value="1" />                                           
                                            </form> 
                                             <form action="/vote" method=post id = vote-form1>  
                                                <button class="btn btn-xs btn-primary btn-block" type="submit" >Vote down</button> 
                                                <input type="hidden" name="match" value="${lineup.matchId.id}" />
                                                <input type="hidden" name="player" value="${lineup.player.id}" />
                                                <input type="hidden" name="voteValue" value="0" />                                          
                                            </form> 
                                    </c:if>             
                                 </c:forEach>               
                            </c:if>

...和js

jQuery(document).ready(function($) {
        $("#vote-form").submit(function(event) {

            // Prevent the form from submitting via the browser.
            event.preventDefault();
            voteViaAjax();

        });
    });

    jQuery(document).ready(function($) {
        $("#vote-form1").submit(function(event) {

            // Prevent the form from submitting via the browser.
            event.preventDefault();
            voteViaAjax();

        });
    });


    function voteViaAjax() {

        var match = $('#match').val();
        var player = $('#player').val();
        var voteValue = $('#voteValue').val();
        var vote = {"player" : player, "match" : match,  "voteValue": voteValue};


        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");

        $.ajax({
            type : "POST",
            contentType : "application/json",
            beforeSend: function(xhr) {
                xhr.setRequestHeader(header, token)
              },
            url : "/vote",  
            data : JSON.stringify(vote),
            dataType : 'json',
            timeout : 100000,
            success : function(data) {
                console.log("SUCCESS: ", data);
                $('#info').html(data);
            },
            error : function(e) {
                console.log("ERROR: ", e);

            },
            done : function(e) {
                console.log("DONE");
            }
        });
    }

控制器版本1的问题我收到错误:

  

&#34;&#34;状态&#34; 400&#34;错误&#34;:&#34;差   请求&#34;&#34;例外&#34;:&#34; org.springframework.web.bind.UnsatisfiedServletRequestParameterException&#34;&#34;消息&#34;:&#34;参数   条件\&#34;匹配,播放器,voteValue \&#34;没有达到实际要求   参数:&#34;

第二个控制器我无法使用,因为我的匹配和播放器是对象,我只发现如何将字符串值作为投票对象的一部分发送。

提前谢谢大家!!!!!

1 个答案:

答案 0 :(得分:1)

您需要混合使用两个控制器。

控制器方法需要@ResponseBody,因此响应被序列化,并且您可能希望发回一个对象而不是字符串。在Spring中,如果控制器返回没有@ResponseBody的String,则String标识要转发的“View”。

您的JavaScript正在发送一个JSON对象,因此您应该拥有@RequestBody,就像控制器2一样。

如果您的Controller仅用于Rest端点,您应该考虑使用@RestController注释,它会自动添加@RequestBody,@ ResponseBody,并为您的控制器方法生成/使用语义。

我在Java方面比JavaScript更好,所以我通常使用PostMan来测试我的服务,或者编写一个测试。一旦我知道了Json的外观,我就会编写JavaScript,如果我收到错误,我会检查浏览器使用开发人员工具发送的内容。

在过去的13年里,我个人编写了很多JSP应用程序。我不是前端开发人员,但在过去的两年里,我已经构建了许多内部应用程序来帮助我们的开发团队。今天我会为任何需要ajax功能的应用程序选择Angular(JS)(唯一的服务器端逻辑是让你将spring模型转换为JS变量)。如果我需要构建一个使用服务器端渲染的应用程序,我不会使用JSP,我会使用Tymeleaf。

相关问题