Reputation: 23
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!!
Upvotes: 2
Views: 10002
Reputation: 3666
adding to oris answer, you need not do a getJSON too. Inside your success callback iterate throw the list a get the messages.
success: function(data) {
for(var count=0; count<data.length; count++){
yourMessage = data[count];
}
//your code
}
Upvotes: 2
Reputation: 7847
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
Upvotes: 8