微信小程序-ajax發post請求 json 和 application/x-www-form-urlencoded

前端向後端傳輸數據時,如果是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,

參考文章:

https://www.cnblogs.com/edwardwzw/p/11694903.html;

https://www.jianshu.com/p/b0d6504c7ccb;

❤如果文章對您有所幫助,就在文章的右上角或者文章的末尾點個贊吧!(づ ̄ 3 ̄)づ

❤如果喜歡大白兔分享的文章,就給大白兔點個關注吧!(๑′ᴗ‵๑)づ╭❤~

❤對文章有任何問題歡迎小夥伴們下方留言或者入羣探討【羣號:708072830】

❤鑑於個人經驗有限,所有觀點及技術研點,如有異議,請直接回復討論(請勿發表攻擊言論)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章