Harry
Harry

Reputation: 4773

Ajax in spring MVC

I am trying to access object using ajax in spring MVC. So its like I have 2 drop downs for country and states when I select country it should update states accordingly. What I have done till now is in my .jsp file

<script>
    function modifyList() {         
        $.post("checklist.html", { country: $('#country').val() }, 
                function(data) { alert(data); });
    }
</script>   

<body>  
    <form:form id="flist" commandName="list">
        <table>         
            <tr>
                <td>
                    <form:label path="country"> Country </form:label>
                </td>
                <td>
                    <form:select path="country" multiple="false" onchange="modifyList()">
                        <form:options items="${list.country}" />
                    </form:select>
                </td>
            </tr>
            <tr>
                <td>
                    <form:label path="state"> State </form:label>
                </td>
                <td>
                    <form:select path="state" multiple="false">
                        <form:options items="${list.state}" />
                    </form:select>
                </td>
            </tr>   
        </table>
</form:form>
</body>

In my controller I have

@RequestMapping(value = "/{path}/checklist", method = RequestMethod.POST)   
public @ResponseBody String list(@RequestParam("country") String country) { 
    System.out.println("selected country" + country);
    return country;
}

This works fine and returns me the country name in alert but my problem is I want to populate my state drop down according to the country selected. Is it possible that I can return the whole list object? If yes then how I can read that object and populate my state dropdown?

Upvotes: 1

Views: 3328

Answers (2)

francadaval
francadaval

Reputation: 2481

As you are using jQuery you should send a get ajax request (make a search in jquery api). Then, if your MVC controller returns a list, your returned data will be a JSON list and from data[0] to data[data.length-1] you will have the states.

You can also return a list of objects in form {statecode: <code>, statename: <name>} using the equivalent Java bean in the list returned by the controller. In this case you can change names for diferent languages with the same code for selection.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160170

AFAIK the Spring tags don't know anything about Ajax, so you'd need to use JavaScript to remove any existing options and add the new ones returned from the Ajax call.

There are a number of plugins listed on the jQuery site; YMMV. I might consider just doing it by hand, since the code is relatively short.

Upvotes: 1

Related Questions