springmvc.xml配置文件中
<!-- 启动Springmvc注解驱动 -->
<mvc:annotation-driven/>
<!-- 返回json 方法一 需要导入 fastjson.jar包 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
springmvc.xml配置参考链接
http://my.oschina.net/haopeng/blog/324934
controller
@RequestMapping("/getjson" )
@ResponseBody
public ItemCustom testJson( int id) throws Exception {
System. out.println(id);
return it .getCustomById(2);
}
jsp
$.ajax({
url: "${pageContext.request.contextPath }/json/getjson.do?id=1",
contentType: "application/json;charset=utf-8" ,
success: function(data){
var json=$.parseJSON(data);
alert(json.name);
alert(json.id);
alert(json.price);
},
data: '{"id":"2"}',
error: function(){
alert( "获取数据错误" );
},
type: "post",
} )
fastjson的下载链接:
http://repo1.maven.org/maven2/com/alibaba/fastjson/1.2.17/fastjson-1.2.17.jar