Returning a String array from Jquery ajax method using Spring MVC

arrays, jquery, spring-mvc, string

Solution

You don't need to convert to JSON yourself. Spring 3 with `<mvc:annotation-driven` enabled and jackson in the classpath does it for you:

@RequestMapping(value = "/dyn/list", method = RequestMethod.GET)
public @ResponseBody List<String> getList(@RequestParam String list) {
    List<String> newList = new ArrayList<String>();
    newList.add(opt0);
    newList.add(opt1);
    newList.add(opt2);
    return newList;
}

For more info check out this post

Problem

I am trying to dynamically generate a list/dropdown using JQuery's .ajax method. Following is the code I wrote: ``` <script type="text/javascript"> $(document).ready(function() { alert('in doc'); $.ajax({ url: "dyn/list", type: "GET", data: "list="+'', dataType: "json", error: function() {alert('eerrrr');}, success: function(data) { alert('success'); alert(data); $('#seltag').append( $('<option></option>').html(data) ); }, complete: function() {} }); });</script> ``` And my corresponding controller method looks like ``` @RequestMapping(value = "/dyn/list", method = RequestMethod.GET) public @ResponseBody String getList(@RequestParam String list) { ArrayList<String> newList = new ArrayList<String>(); newList.add(opt0); newList.add(opt1); newList.add(opt2); return(new JSONArray(newList).toString()); //return opt0; } ``` Where opt0,1 and 2 are static string variables. Each time an error is returned. I have also tried .getJSON but to no avail. Help me out fellas!!

Original source