JQuery,JSON,Spring MVC – 动态加载选择选项
我有一个像这样的jsp表单……第二个选择框中的值,应该根据第一个选择框(国家)中的值加载状态。 我正在使用AJAX,JSON,Spring MVC来检索结果。
index.jsp的…..
<form:checkboxes items="${skillsList}" path="skills" itemLabel="description" itemValue="id" delimiter="
" /> <form:checkboxes items="${languagesList}" path="languages" itemLabel="description" itemValue="id" delimiter="
" />
控制器….
@RequestMapping(value="stateslist.html") public @ResponseBody List sectionList(@ModelAttribute("search") SearchForm search, @RequestParam(value="countryId", required=true) String countryId, ModelMap modelMap){ return stateService.getStates(countryId); }
JQuery部分….
function getStates(){ $.getJSON( "stateslist.html", {countryId: $('#country').val()}, function(data) { var html = ''; var len = data.length; for(var i=0; i<len; i++){ html += '' + data[i].name + ''; } $('#state').append(html); } ); } $(document).ready(function() { $('#country').change(function() { getStates(); }); });
我可以看到调试器将ajax请求提交给Spring控制器,它确实返回一个State对象列表,其中包含id,name等字段……问题是状态选择选项没有改变。似乎是那个function(data){....}
部分不起作用。有人帮助我,我在这里做错了…
—更新—
我已经从回调函数中删除了所有东西,只是有了…
function(data){alert("something");}
即使这不起作用……这意味着呼叫永远不会达到那个部分……
我有相同的代码,其中city(cityId)值根据country(countryId)选择进行更改。 它非常完美:
$("select#countryId").change(function(){ $.getJSON("getCityList.do",{countryCode: $(this).val()}, function(j){ var options = ''; for (var i = 0; i < j.length; i++) { options += ''; } $("select#cityId").html(options); }); });
所以我认为你只需要添加“select”前缀。
我更新你的控制器方法,以避免406 Not Acceptable
错误:
@RequestMapping(value="stateslist.json") @ResponseStatus(HttpStatus.OK) public @ResponseBody List sectionList(@ModelAttribute("search") SearchForm search, @RequestParam(value="countryId", required=true) String countryId, ModelMap modelMap){ return stateService.getStates(countryId); }
和你的JQuery部分:
将以下依赖项添加到您的pom.xml
:
com.fasterxml.jackson.core jackson-databind 2.5.0
最后在控制器类中添加@ResponseBody
注释。