微信小程序開發中網絡請求必不可少.GET .POST請求是最常用的.GET請求,POST請求的時候有好幾個坑.我已經為大家填好了.
之前的.GET 請求都是如下這樣寫:(給大家舉個例子)
wx.request({ url: url, data: { teacherid: teacherid }, header: { 'content-type': 'application/json' }, success: (res) => { // console.log(res.data);
this.setData({ testpaper: res.data.testpaper, teacher : res.data.teacher }); } })
但是post方式提交的話就有所改變了,給大家列出以下幾點注意事項:
1. 'Content-Type': 'application/json'用在get請求中沒問題.
POST請求就不好使了.需要改成 : "Content-Type": "application/x-www-form-urlencoded"
2. 加上 method: "POST"
3. data: { answer : { "a":10,"b":8,"c":6 } } 寫成json格式這樣也是請求不到數據的.需要轉格式.
這里我用JSON.Stringify() 將json對象轉換成json字符串格式
部分代碼分享給大家,這里answer與student 都是json對象格式需要轉換
wx.request({ url : "https://www.", method: "POST", data: { answer : JSON.stringify(this.data.answer), score : _score, pjid : this.data.pj.pjid, testpaperid : this.data.pj.testpaperid, student : JSON.stringify(this.data.student), message : this.data.message }, header: { "Content-Type": "application/x-www-form-urlencoded" }, success: function (res) { console.log(res.data); wx.navigateBack({ delta: 1 //小程序關閉當前頁面返回上一頁面
}) wx.showToast({ title: '評教成功!', icon: 'success', duration: 2000 }) }, })
