I'm trying to populate a dropdown list from a jQuery call that requires JSON. I found on the web the following code which is my starting point (Java and Spring 3), but I accept other/better approaches:
The JSP (only relevant code shown):
<script language="JavaScript">
$(document).ready(function() {
$('#parkName').change(
function(){
alert($(this).val());
$.getJSON('${findUnitsURL}', {
parkName : $(this).val(),
ajax : 'true'
}, function(data) {
var html = '<option value="">City</option>';
var len = data.length;
for ( var i = 0; i < len; i++) {
html += '<option value="' + data[i].name + '">'
+ data[i].name + '</option>';
}
html += '</option>';
$('#parkUnitTitleAersa').html(html);
});
});
});
</script>
<div id="content">
<form:form method="post" action="mainForm" commandName="mainForm">
<form:select id="parkName" path="parkName">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${parkList}" />
</form:select>
<form:select id="parkUnitTitleAersa" path="parkUnitTitleAersa">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${parkUnitList}" />
</form:select>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form:form>
</div>
Java controller who has the requested method:
@RequestMapping(value = "units", method = RequestMethod.GET)
public @ResponseBody List<String> unitsForPark(@RequestParam(value = "parkName", required = true) String parkName) {
List<String> l = new ArrayList<String>();
l.add("AA01");
l.add("AA02");
l.add("LA03");
l.add("SG04");
return l;
}
When I select a value in "parkName" dropdown the other is not populated. Using firebug I get this error:
[10:46:39.881] GET http://localhost:8084/SpringBlog/units?parkName=LA&ajax=true [HTTP/1.1 406 No Aceptable 62ms]
Any idea? Thanks!!
406points to a Spring problem in that Spring doesn't know how to create aJSONview of the data, since$.getJSONis setting the headerAccept: application/json. You should look at Spring's ContentNegotiatingViewResolver and MappingJacksonJsonView