Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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;
}
like image 824
Bboy820602 Avatar asked Oct 02 '14 08:10

Bboy820602


People also ask

What are the parameters of AJAX?

The parameters specifies one or more name/value pairs for the AJAX request. The data type expected of the server response. A function to run if the request fails. A Boolean value specifying whether a request is only successful if the response has changed since the last request.


1 Answers

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

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

And in Spring MVC the controller:

@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;
}
like image 61
Pracede Avatar answered Sep 20 '22 13:09

Pracede