简体   繁体   English

Spring Boot应用程序中的Ajax POST请求

[英]ajax POST request in spring boot app

I am trying to perform an action on server without navigation or refreshing the page. 我试图在服务器上执行操作而不导航或刷新页面。 As i understand i need to use AJAX call. 据我了解,我需要使用AJAX调用。 I have tried two approaches but getting problems. 我尝试了两种方法,但遇到了问题。

Controller version 1: 控制器版本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;

                }

Controller version 2: 控制器版本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: 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>

... and the js ...和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");
            }
        });
    }

The problem with version 1 of controller i am getting the error : 控制器版本1的问题我得到了错误:

""status":400,"error":"Bad Request","exception":"org.springframework.web.bind.UnsatisfiedServletRequestParameterException","message":"Parameter conditions \\"match, player, voteValue\\" not met for actual request parameters:" “”状态“:400,”错误“:”错误的请求“,”异常“:” org.springframework.web.bind.UnsatisfiedServletRequestParameterException“,”消息“:”参数条件\\“比赛,球员,投票值\\”不满足对于实际的请求参数:”

The second controller i cant use because my Match and Player are object , and i found only how to send the String values as part of the Vote object. 我不能使用的第二个控制器,因为我的Match和Player是object,并且我仅找到了如何将String值作为Vote对象的一部分发送。

Thank you all in advance!!!!! 谢谢大家!!!!!

You need a mix of the two controllers. 您需要同时使用两个控制器。

The controller method needs to have @ResponseBody, so the response is serialized, and maybe you want to send back an object not a string. controller方法需要具有@ResponseBody,因此响应已序列化,也许您想发送回一个对象而不是字符串。 In Spring if a controller returns a String without @ResponseBody then the String identifies the "View" to forward to. 在Spring中,如果控制器返回不带@ResponseBody的字符串,则该字符串标识要转发到的“视图”。

Your JavaScript is sending a JSON object so you should have @RequestBody, like controller 2. 您的JavaScript正在发送JSON对象,因此您应该具有@RequestBody,例如控制器2。

If your Controller is only used for Rest endpoints, you should consider using the @RestController annotation, it automatically adds @RequestBody, @ResponseBody, and produce/consume semantics to your controller methods. 如果Controller仅用于Rest终结点,则应考虑使用@RestController批注,它会自动将@ RequestBody,@ ResponseBody添加到控制器方法中并产生/使用语义。

I'm much better at Java than JavaScript, so I typically test my service using PostMan, or write a test. 我在Java方面比JavaScript更好,因此我通常使用PostMan测试我的服务或编写测试。 Once I know how the Json should look, I write the JavaScript, if I get an error back I check what the browser sent using developer tools. 一旦知道了Json的外观,就编写JavaScript,如果返回错误,则检查使用开发人员工具发送的浏览器。

Personally I have written a lot of JSP applications during the last 13 years. 我个人在过去13年中编写了许多JSP应用程序。 I'm not a front end developer, but during the last 2 years I have built a number of internal application to help our development team. 我不是前端开发人员,但是在过去的两年中,我构建了许多内部应用程序来帮助我们的开发团队。 Today I would choose Angular(JS) for any application that needs ajax capabilities (the only server side logic is getting you spring model into JS variables). 今天,对于需要ajax功能的任何应用程序,我都会选择Angular(JS)(唯一的服务器端逻辑是将模型引入JS变量)。 If I need to build an app that uses serverside rendering I would not use JSP, I would use Tymeleaf. 如果我需要构建一个使用服务器端渲染的应用程序,那么我将不使用JSP,而应使用Tymeleaf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM