ajax提交json数据
consumes = "application/json"–作为请求头告诉服务端消息主体是序列化的JSON字符串 application/x-www-form-urlencoded–在发送前编码所有字符(默认) multipart/form-data–不对字符编码。在使用包含文件上传控件的表单时,必须使用该值 text/plain–空格转换为 “+” 加号,但不对特殊字符编码。
controller层方法
@Controller
@RequestMapping("/dept2")
public class DepartmentController2 {
private static final Logger l
= LoggerFactory
.getLogger(DepartmentController2
.class);
@Autowired
IDepartmentService iDepartmentService
;
@RequestMapping(path
="/addUI",method
= RequestMethod
.GET
)
public String
addUI(){
return "add_dept";
}
@RequestMapping(path
="/add",method
= RequestMethod
.POST
,consumes
= "application/json")
public @ResponseBody
Object
add(@RequestBody Department dept
){
l
.info("add dept="+dept
);
try {
iDepartmentService
.saveDepartment(dept
);
return Result
.init(200,"添加成功",null
);
} catch (Exception e
) {
e
.printStackTrace();
}
return Result
.init(-200,"添加失败",null
);
}
}
add_dept.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<head>
<title>Title
</title>
<script type="text/javascript" src="${path}/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(function () {
$('#btn_add').click(function () {
var dname= $('#add_dname').val()
console.info(dname)
$.ajax({
url:'${path}/dept2/add',
async:true,
data:'{"did":"","dname":"'+dname+'"}',
type:"post",
contentType:"application/json;charset=UTF-8",
success:function (result) {
if(200==result.code){
alert(result.msg)
}
},
error:function () {
alert('服务问题,请求失败')
}
});
})
})
</script>
</head>
<body>
<div id="addDiv">
<h1>添加页面
</h1>
<form id="add_form" >
<input type="hidden" name="did" id="add_did"/><br/>
<input type="text" name="dname" id="add_dname"/><br/>
<input id="btn_add" type="button" value="保存"/><br/>
</form>
</div>
</body>
</html>
使用postman测试发送json数据