以下是 SpringMVC 控制器代码片段:
@RequestMapping(value = "/getCityList", method = RequestMethod.POST)
public @ResponseBody LinkedHashMap<String, String> getCityList(@RequestParam(value = "countryCode") String countryCode, HttpServletRequest request) throws Exception {
//gets ordered city list of country [sorted by city name]
LinkedHashMap<String, String> cityList = uiOperationsService.getCityList(countryCode);
for (String s : cityList.values()) {
System.out.println(s); //prints sorted list [sorted by name]
}
return cityList;
}
以下是ajax调用:
function fillCityList(countryCode) {
$.ajax({
type: "POST",
url: '/getCityList',
data: {countryCode:countryCode},
beforeSend:function(){
$('#city').html("<option value=''>-- SELECT --</option>" );
}
}).done(function (data) {
console.log(data); // UNSORTED JSON STRING [Actually sorted by key... not by city name]
})
}
为什么从getCityList方法返回的已排序的LinkedHashMap在返回过程中变成了未排序的JSON对象?这是为什么呢? 是否因为ResponseBody注解将LinkedHashMap转换为HashMap? 我可以通过Gson库将我的已排序对象转换为JSON字符串,并从我的getCityList方法返回JSON字符串,但我不喜欢这个解决方案。 我该怎么做才能向JavaScript回调方法提供已排序列表呢?
<form:options items="${cityList}"></form:options>
。但是我认为不情愿地应该例外,并将返回ajax调用响应的方法中的LinkedHashMap转换为List。 - yuceel