前端json資料 到 自動後臺轉換為物件 Spring
阿新 • • 發佈:2019-01-27
後臺可以使用 @ModelAttribute 、 @RequestBody
都是根據被轉換的物件的欄位依次從請求引數中獲取對應的欄位設定值。
前端有所不同:
data 一個要的json字串, 一個是 json物件
1. @RequestBody
$.ajax({
type: "post",
contentType: 'application/json;charset=UTF-8', //必須這麼寫; 表示傳遞的引數 是 json型別的
dataType:'json',//非必須
data: JSON.stringify({ //必須轉換為json字串傳遞 ,要直接傳該字元,否則就是錯誤。
userName: 'xxx'
} ),
url: 'user/save',
success: function (res) {
console.log(res );
}
});
2. @ModelAttribute
$.ajax({
type: "post",
//contentType: 'application/x-www-form-urlencoded;charset=UTF-8',//這是預設的 請求型別
data: { //必須轉換為json字串 ,直接傳jsonuserName: 'xxx'
} ,
url: 'user/save',
success: function (res) {
console.log(res);
}
});