使用Spring 的@ResponseBody 标签 可以方便的和表示层进行交流。悲催的是貌似只有spring 3.1.x 使用的时候没问题,我之前 是用的4.1.x ,但使用时返回到前端总出406的错误,但换成3.1.x后就没问题了,上网搜了下, 确实有这个毛病,也只能忍了,又不想去动源码,暂时用3.1.x吧。
大概情况如下:
配置文件里要加上 <mvc:annotation-driven />
POM文件里加入依赖
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Controller层如下
@RequestMapping(value = "terminal/getzdxh/{id}", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> getzdxh(Model model,@PathVariable String id) {
System.out.println(id);
Map<String, Object> modelMap = new HashMap<String, Object>(3);
modelMap.put("total", "1");
modelMap.put("data", componentService.getTerminalTypeByFactory(id));
modelMap.put("success", "true");
return modelMap;
}
前台页面如下
$.ajax({
type: "GET",
contentType: "application/json;charset=utf-8",
url: "${ctx}"+"/terminal/getzdxh/"+victype,
dataType: "json",
async:false,
success:function(data){
alert(data);
$.each(data, function(key,value){
if(key=='data') {
alert(JSON.stringify(value));
$.each(value,function(n,value) {
html += '<option value="'+value.typeCode+'">'+value.typeDesc+'</option>';
});
}
})
$("#zdxhList").html(html);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.readyState);
alert(XMLHttpRequest.responseText);
alert(XMLHttpRequest.responseXML);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.statusText);
alert(textStatus);
alert(errorThrown);
}
});