您的位置:首頁技術文章
文章詳情頁

微信小程序 post請求

瀏覽:114日期:2022-07-16 08:13:58

微信小程序開發中網絡請求必不可少.GET.POST請求是最常用的.GET請求,POST請求的時候有好幾個坑.我已經為大家填好了.

<img src=" 6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" align="middle" alt="" />

按照文檔,肯定是這么寫.那就入坑了.

1. 'Content-Type': 'application/json'用在get請求中沒問題.

POST請求就不好使了.需要改成: "Content-Type": "application/x-www-form-urlencoded"

2016.11.10更新:有同學在將content-type 修改為小寫后,post請求成功.

2. 加上method: "POST"

3.data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }寫成json格式這樣也是請求不到數據的.需要轉格式.

下面直接貼代碼:

3.1

<span style="font-size:24px;">//index.js //獲取應用實例 var app = getApp() Page( { data: { toastHidden: true, city_name: '', }, onLoad: function() { that = this; wx.request( { url: "http://op.juhe.cn/onebox/weather/query", header: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", //data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }, data: Util.json2Form( { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" }), complete: function( res ) { that.setData( {toastHidden: false,toastText: res.data.reason,city_name: res.data.result.data.realtime.city_name,date: res.data.result.data.realtime.date,info: res.data.result.data.realtime.weather.info, }); if( res == null || res.data == null ) {console.error( '網絡請求失敗' );return; } } }) }, onToastChanged: function() { that.setData( { toastHidden: true }); } }) var that; var Util = require( '../../utils/util.js' );</span>

3.2

<span style="font-size:24px;"><!--index.wxml--> <view class="container"> <toast hidden="{{toastHidden}}" bindchange="onToastChanged"> {{toastText}} </toast> <view>{{city_name}}</view> <view>{{date}}</view> <view>{{info}}</view> </view></span>

3.3

<span style="font-size:24px;">//util.js function json2Form(json) { var str = []; for(var p in json){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); } return str.join("&"); } module.exports = { json2Form:json2Form, }</span>

微信小程序 post請求

希望對大家有幫助.

分享一個做得比較好的微信小程序:

微信小程序 post請求

標簽: 微信
相關文章:
国产综合久久一区二区三区