前端向後端傳輸數據時,如果是get傳輸,直接傳在url後;
url: this.data.host + '/student/get?teacherId=' + teacherId + '&studentId=' + studentId,
method: 'get',
如果是post傳輸,則在請求體body中傳輸。
url: this.data.host + '/student/getList',
method: 'get',
data:{
"teacherId ":this.data.teacherId ,
"teacherId ":this.data.teacherId ,
}
put提交方式:
url: that.data.host + '/student/update',
method: 'PUT',
data: {
teacherId: teacherId,
},
delete提交方式:
wx.request({
url: this.data.host + '/student/delete?teacherId=' + teacherId + '&studentId=' + studentId,
method: 'DELETE',
success: function(res) {
//成功執行事件
}
}
})
- 對於
POST
方法且header['content-type']
爲application/json
的數據,會對數據進行 JSON 序列化 - 對於
POST
方法且header['content-type']
爲application/x-www-form-urlencoded
的數據,會將數據轉換成 query string
=================================================================================
在body中的數據格式又有兩種,一種是 json 數據格式,另一種是 字符串。具體要用哪種格式取決於後端入參的格式。
如果後端接收json數據類型,post 的 headers 需要設置;,傳給後端的數據就形如 { "teacherId","6596a4b268634e2baf11a569a8fa4b77"}
header: {
'content-type': 'application/json' // 默認值
},
如果後端接收的是(表單)字符串類型,post 的 headers 需設置 { ‘content-type’: ’application/x-www-form-urlencoded’ },
,傳輸給後端的數據就形如 'name=張三&age=22';
ajax默認數據格式爲json,所以:
1.當後端需要接收json格式的數據時,post請求頭不需要設置請求頭,數據格式也不需要我們去轉換(若數據已經是json);
2.當後端需要接收字符串格式的數據時,我們需要給post請求頭設置
header: {
//'content-type': 'application/json' // 默認值
'content-type': 'application/x-www-form-urlencoded'
},
接收 json格式的數據格式
ajax請求中content-type:application/json代表參數以json字符串傳遞給後臺,controller接收需要@RequestBody 接收參數
例如:@RequestBody Map<String, Object> map,也可以使用類接收@RequestBody User user
接收form表單 字符串格式的數據
ajax請求中content-type:application/x-www-form-urlencoded代表參數以鍵值對傳遞給後臺,controller接收可以單個參數接收,例如:@RequestParam("param") String param;也可以用類接收User user,
參考文章: