(1)MVC的controller中
@RequestMapping(value="/alarm",method=RequestMethod.GET)
public JSONObject alarmSystem(@RequestParam Integer factoryId){
Map<String, Object> alarmMap = factoryService.getAlarmInfoByFactoryId(factoryId);
new ModelAndView().setViewName("alarm");//跳转到arlarm.jsp
JSONObject jsonObject = new JSONObject();
jsonObject.put("alarmMapJson",alarmMap);//将map封装成json数据
System.out.println("jsonObject数据:"+jsonObject.toString());
return jsonObject;
}
控制台输出的jsonObjtect
{"alarmMapJson":{"alarm1_name":"TAL1203","factory_id":1,"alarm1_content":"TI1203低报警","alarm2_name":"TAH1203","alarm2_content":"TI1203高报警","alarm_url":"kf0001"}}
(2)alarm.jsp
<body onload="refresh()">
<script type="text/javascript">
function refresh(){
$.ajax({
url: "${pageContext.request.contextPath}/alarm.html?factoryId=1",
type: 'get',
success: function (data) {
alert(data);
},
error:function () {
console.log("发送请求失败");
}
});
}
</script>
结果给我返回html
加了个dataType:’json’,
消息头状态码200,说明ajax发送状态正常,但是返回的数据不是json数据,所以执行error的回调函数。
(3)得出结论:我以为服务器返回的jsonObject对象是json数据,实际上是我太傻,根本不是json数据,而是HTML文档。
(4)所以我要做的就是返回在controller中返回真正的json数据
(5)服务器利用流向页面输出application/json类型的数据
@RequestMapping(value="/alarm",method=RequestMethod.POST)
public void alarmSystem(HttpServletResponse response){
log.info("正在处理alarm页面传来的ajax请求");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
jsonObject.put("alarmMap",factoryService.getAlarmInfoByFactoryId(1));
System.out.println("jsonObject数据为:"+jsonObject.toString());
PrintWriter out = null;
try {
out = response.getWriter();
out.println(jsonObject.toString());
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}