java_dude
java_dude

Reputation: 4088

Making jQuery call to Spring Controller with additional param

On change in a text field the jQuery makes a call to Spring Controller. My question is how does this query sends the @RequestParam to the Controller method controller/find?

How would I be able to send additional Param in this call?

    $(document).ready(function() {
        $( "#id" ).autocomplete({
            source: "${pageContext. request. contextPath}/controller/find.htm"
        });

    });

This works

    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public @ResponseBody
    List<String> findItem(@RequestParam("term") String id)

But need something like

    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public @ResponseBody
    List<String> findItem(@RequestParam("term") String id, Additional param here ??)

Upvotes: 1

Views: 8155

Answers (1)

kryger
kryger

Reputation: 13181

If you pass a function to Autocomplete's source option (rather than just the string to specify the URL) you can define your own data structure to be sent to the server:

$('#id').autocomplete({
    source: function (request, response) {
        $.ajax({
            url: './controller/find.htm',
            data: {
                term: request.term,
                extraParam: 'foo'
            },
            success: function (data) {
                console.log('response=', data);
            }
        });
    }
});

Now the autocomplete requests will contain two parameters: term and extraParam (jsFiddle: http://jsfiddle.net/gtBUt/, open your browser's Network Traffic tab to see what's sent).

The controller can then handle this input like this:

@RequestMapping(value = "/find", method = RequestMethod.GET)
@ResponseBody
public List<String> findItem(@RequestParam("term") String term,
                             @RequestParam("extraParam") String extraParam) {
    ...
}

Upvotes: 7

Related Questions