【发布时间】:2013-08-22 08:02:47
【问题描述】:
我正在使用以下 JQuery、JSP 和 Controller 在我的应用 JSP 页面上更改国家/地区下拉菜单时返回城市列表,但我认为 JQuery 中的 dataType、成功参数不正确,因为我没有得到返回列表。那么有人可以告诉我我在这里做错了什么以及如何在更改国家下拉菜单后获取城市列表以将它们添加到城市下拉菜单中?
感谢您的宝贵时间
<script type="text/javascript">
function loadCity(){
var countryData="countryId="+$(country).val();
$.ajax({
type: "POST",
url: "LoadCities.htm",
data:countryData,
dataType: "javascript",
success: function(cities){
loadCities(eval(cities))
}
});
}
function loadCities(citiesLst){
clearCitiesDD();
for(var i=0;i<citiesLst.length;i++){
var city=citiesLst[i];
appendCity(city.id,city.value);
}
}
function clearCitiesDD(){
$('#cityDD').find('option').remove();
}
function appendCity(id,cityName){
$('#cityDD').append($("<option id='"+id+"'>" + cityName + "</option>"));
}
}
</script>
在我的应用程序控制器中,我有以下代码:
@RequestMapping(value = "/LoadCities.htm", method = RequestMethod.GET)
public @ResponseBody
List<City> getCityByCountryID(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<City> list=
icitys.getCitiesByCountry(Long.parseLong(request.getParameter("countryID")));
return list;
}
在 JSP 文件中,我有以下城市和国家/地区下拉菜单:
<tr>
<td align="right">Country</td>
<td align="left">
<select id ="country" name="country" onchange="loadCity()">
<option value="0">--select--</option>
<c:forEach var="countrylst" items="${countriesList}">
<option value="${countrylst.id}">${countrylst.countryName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td align="right">City</td>
<td align="left">
<select id="cityDD" name="cityDD">
<option value="0">--select--</option>
</select>
</td>
</tr>
【问题讨论】:
-
您是否检查了控制台中的响应以确保其格式符合您的预期?
-
@RoryMcCrossan 检查了萤火虫中的响应并没有得到任何东西:(这是否意味着我的代码是正确的?!
-
不,这意味着您在 JSP 中的
getCityByCountryID没有返回任何内容。 -
@RoryMcCrossan 不,我 100% 肯定它返回并且我已经测试过它从 Controller 类返回结果,问题是从 getCityByCountryID 返回的数据没有显示在 JSP 中
-
没错。您可能需要遍历列表并将每条记录写入 HTML 输出。或者,您可以使用 JSON 编码器,假设 JSP 有一个?
标签: java javascript jquery jsp