前端之家收集整理的这篇文章主要介绍了
Ajax进行POST提交,Spring MVC整合fastJson,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近在学习前端基础,在学习的时候,使用Ajax进行表单提交的时候,发现整合的Spring MVC会报出415错误,经过学习,重新将Spring MVC和fastJson整合。
@H_
403_2@1,使用Ajax进行提交
$.ajax({
type: "POST",
contentType : "application/json",
url: "<%=basePath%>addBean.do",
data: JSON.stringify(beanModel),
dataType: 'json',timeout: 600000,success : function(data) {
console.log("SUCCESS: ",data);
display(data);
},error : function(e) {
console.log("ERROR: ",e);
display(e);
},done : function() {
console.log("DONE");
}
})
@H_
403_2@2,引入fastJson.jar包。
@H_
403_2@3,配置xml
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
@H_
403_2@4,编写controler
代码
@ResponseBody
@RequestMapping(value="/addBean.do",method = RequestMethod.POST)
public String addCrawlerBean(@RequestBody BeanModel beanModel) {
return "Result";
}
@H_
403_2@说明:
@ResponseBody表示的是返回的为直接传输的数据,将不会再去匹配先关的JSP了。
@RequestBody会去
自动组装为相关的bean数据。
@H_
403_2@PS:坑。。。。。。。。。。。。。。 在提交的时候,发现,ajax提交的请求无法请求到Spring MVC里面去!!!奇怪了。但是,在请求的JavaScript
函数当中,如果用一个alert弹出
页面,即可请求到服务器去。于是乎,抓包发现,ajax的post请求的状态为NS_Binding_Aborted。经过网上的查证,发现是还没有响应这个ajax的时候,这个
页面被刷新了。后来才发现,原来form表单中,不能使用button这个
标签,而是要用input
标签,type=“button”,这样不会刷新
页面,于是每次都可以请求成功了。