jQuery – 填充下拉列表的JSON

我正在尝试从需要JSON的jQuery调用填充下拉列表。 我在网上发现了以下代码,这是我的起点(Java和Spring 3),但我接受其他/更好的方法:

JSP(仅显示相关代码):

 $(document).ready(function() { $('#parkName').change( function(){ alert($(this).val()); $.getJSON('${findUnitsURL}', { parkName : $(this).val(), ajax : 'true' }, function(data) { var html = 'City'; var len = data.length; for ( var i = 0; i < len; i++) { html += '' + data[i].name + ''; } html += ''; $('#parkUnitTitleAersa').html(html); }); }); });  

具有所请求方法的Java控制器:

 @RequestMapping(value = "units", method = RequestMethod.GET) public @ResponseBody List unitsForPark(@RequestParam(value = "parkName", required = true) String parkName) { List l = new ArrayList(); l.add("AA01"); l.add("AA02"); l.add("LA03"); l.add("SG04"); return l; } 

当我在“parkName”下拉列表中选择一个值时,另一个未填充。 使用firebug我收到此错误:

 [10:46:39.881] GET http://localhost:8084/SpringBlog/units?parkName=LA&ajax=true [HTTP/1.1 406 No Aceptable 62ms] 

任何的想法? 谢谢!!

406指向一个Spring问题,因为Spring不知道如何创建数据的JSON视图,因为$.getJSON正在设置标题Accept: application/json 。 你应该看一下Spring的ContentNegotiatingViewResolver和MappingJacksonJsonView

假设您的Spring Web应用程序的上下文配置中已经有 ? 如果是这样,那么可能只是jackson在运行Spring时不在类路径上。 如果使用Maven,Ivy,Gradle(或其他依赖管理/构建工具),只需手动将其添加到classpath或作为依赖项。