使用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);
}
});