post請求兩種傳輸格式傳輸複雜資料
阿新 • • 發佈:2019-01-09
1.post請求,預設傳輸格式application/x-www-form-urlencoded,data是物件,使用鍵值對,傳輸複雜資料
var y={ id:5, name: "張三", city:"上海", } var x={ sex:'男', user:y, }; $("#aaa").click(function () { $.post({ url:'/hello/aaa', //contentType:"application/json;charset=utf-8", data:{obj:JSON.stringify(x)}, success:function(data){ alert(data); } }); });
後臺接收
public User aaa(String obj){
JSONObject jobj=JSON.parseObject(obj);
String sex=jobj.getString("sex");
String user1=jobj.getString("user");
User user=JSON.parseObject(user1,User.class);
return user;
}
2.post請求contentType:"application/json;charset=utf-8",data必須是json字串,後臺接收要加@RequestBody,傳輸複雜資料
var y={ id:5, name: "張三", city:"上海", } var x={ sex:'男', user:y, }; $("#aaa").click(function () { $.post({ url:'/hello/aaa', contentType:"application/json;charset=utf-8", data:JSON.stringify(x), success:function(data){ alert(data); } }); });
後臺接收
(1)
public User aaa(@RequestBody String obj){
JSONObject jobj=JSON.parseObject(obj);
String sex=jobj.getString("sex");
String user1=jobj.getString("user");
User user=JSON.parseObject(user1,User.class);
return user;
}
(2)
public User aaa(@RequestBody Map<String,Object> ma){
String sex=ma.get("sex").toString();
Map<String,Object> ma1=(Map<String,Object>)ma.get("user");
String s=JSON.toJSONString(ma1); //map轉json字串
User user=JSON.parseObject(s,User.class); //json字串轉實體類
return user;
}
總而言之就是:如果沒加contentType:"application/json",那麼data就應該對應的是物件;反之,如果加了contentType:"application/json",那麼ajax傳送的就必須是字串。