【问题标题】:How to send and receive ajax request with parameter in Spring Framework?如何在 Spring Framework 中发送和接收带参数的 ajax 请求?
【发布时间】:2014-11-27 04:50:23
【问题描述】:

我正在尝试使用 ajax 发送请求,但状态为 400 错误请求。 我应该发送什么样的数据以及如何在控制器中获取数据? 我确定请求没问题,只是参数出错了

jsp

<script type="text/javascript">

    var SubmitRequest = function(){
        $.ajax({
                url : "submit.htm",
                data: document.getElementById('inputUrl'),
                type: "POST",
                dataType: "text",
                contentType: false, 
                processData: false,
                success : 
                    function(response) {
                        $('#response').html(response);
                    }
        });
    }
    </script>

控制器

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public @ResponseBody
String Submit(@RequestParam String request) {
    APIConnection connect = new APIConnection();
    String resp = "";
    try {
        resp = "<textarea  rows='10'cols='100'>" + connect.doConnection(request) + "</textarea>";
    } catch (Exception e) {
        // TODO Auto-generated catch block
        resp = "<textarea  rows='10'cols='100'>" + "Request failed, please try again." + "</textarea>";
    }
    return resp;
}

【问题讨论】:

    标签: javascript jquery ajax spring spring-mvc


    【解决方案1】:

    要发送 Ajax 发布请求,您可以使用:

    $.ajax({
         type: "POST",
         url: "submit.htm",
         data: { name: "John", location: "Boston" } // parameters
    })
    

    在 Spring MVC 中,控制器:

    @RequestMapping(value = "/submit.htm", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    String Submit(@RequestParam("name") String name,@RequestParam("location") String location) {
        // your logic here
        return resp;
    }
    

    【讨论】:

    • 有什么办法可以用RequestBody代替RequestParam
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多