日期:2014-05-16  浏览次数:20418 次

spring mvc 返回json格式
前端:
用jquery发送ajax请求

        $.ajax({
type: "POST",
url: "xxx",
data: "name=John&location=Boston",
dataType:"json",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
cache:false,
success: function(msg){
//alert( "Data Saved: " + msg );
alert( "Data Saved: " + msg.name + msg.name2);
alert( "Data Saved: " + msg.test1 + msg.test2);
}
});

其中:dataType有四种选择,xml, json, script, or html


后台:
接收前端发送的请求

        public ModelAndView getResult(HttpServletRequest request, HttpServletResponse response){
System.out.println(request.getParameter("name"));
System.out.println(request.getParameter("location"));
Map model = new HashMap();
model.put("name", "fangjun");
model.put("name2", "james");
ModelAndView view = new ModelAndView(new MappingJacksonJsonView(), model);
view.addObject("test1", 123);
view.addObject("test2", 456);
view.addObject("test3", 789);
return view;
}
重点注意:new MappingJacksonJsonView()


总结1:通过map和view.addObject两种方式都可以设置json类型名值对。
总结2:ajax异步请求。跟刷新页面无关。view不用设置页面跳转。