register.jsp:
$("#sub").click(function(){
var m = {
"account": $("#_account").val(),
"passwords": $("#_pass").val(),
"realname": $("#real_name").val(),
"phonenumber": $("#phone_number").val(),
"sex": $("input:checked").val(),
"mailname": $("#mail_name").val()
};
$.ajax({
type:"POST",
async : false,
url:"/demo/user/receive",
dataType:"json",
contentType:"application/json; charset=utf-8",
data:JSON.stringify(m),
success:function(data){
alert("return map success!");
newpage();
},
error:function(data){
alert("保存失敗 ")
}
})
Controller:
@RequestMapping(value="receive", method=RequestMethod.POST, consumes="application/json") public @ResponseBody Map<String, String> receiveData(@RequestBody RegInfo info){ Map<String, String> reg_check = regInfoService.checkRegInfo(info); for(Map.Entry<String, String> entry:reg_check.entrySet()){ System.out.println(entry.getKey()+"--->"+entry.getValue()); } System.out.println(info); System.out.println(info.getRealname()); return reg_check; }
1.如上代碼中data需要為String形式的數據,由於此處m是json對象,因此需要使用JSON.stringify()轉換為字符串形式的數據即“m”;
2.@requestbody用於接收前台傳來的數據,接收到的數據為字符串的形式,但是此注解可以將字符串中的變量值注入到對象info中,要求info實體中的屬性名字和m中屬性一致;
3.@responsebody用於將后台的數據直接放在responsebody中返回,此處@responsebody注解會將map的實例轉換為json對象,故在前端data接收到的是json對象;
4.consumes表示只處理格式為content-type:application/json的請求;相對的produces="application/json"表示僅處理請求中包含accept:application/json(即返回類型為application/json格式)的request;
注:ajax中
data:String
默認情況下自動轉換為String類型;可用processdata屬性禁止自動轉換;
processData:Boolean
默認情況下為true;為false表示禁止自動轉換data中數據為請求字符串;
本人還是有點疑問:既然data默認會自動轉換為字符串,為什么還要JSON.stringify()轉換;(測試不使用的話傳遞失敗)