Javascript 如何在Spring Framework中发送和接收带有参数的ajax请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26156748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:25:56  来源:igfitidea点击:

How to send and receive ajax request with parameter in Spring Framework?

javascriptjqueryajaxspringspring-mvc

提问by Bboy820602

I'm try to send a request with ajax but have status 400 bad request. what kind of data should i send and how to get data in controller? I'm sure that request is fine only the parameter go wrong

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

jsp

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>

controller

控制器

@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;
}

回答by Pracede

To send an Ajax post request, you could use this :

要发送 Ajax post 请求,您可以使用以下命令:

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

And in Spring MVC the controller:

在 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;
}