微信小程序 POST請求的實例詳解
在微信小程序里post請求和get情求,寫法差不多,但是還是有一點點不同的,下面利用post請求做一個查詢天氣的微信小程序demo。
頁面代碼:
<view> {{title}} </view><span style="font-size:24px;"><!--index.wxml--> <view class="container"> <view style="color:{{red}}">{{city_name}}</view> <view>{{date}}</view> <view>{{info}}</view> </view></span>js代碼:
var app = getApp();var that; var Util = require( '../../utils/util.js' );Page( { data: { city_name: '', title:'', red:'green' }, onLoad: function(options) { this.setData({ title:options.title }) that = this; wx.request( { url: "http://op.juhe.cn/onebox/weather/query", header: { //請求頭和ajax寫法一樣 "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", data: Util.json2Form( { cityname: "北京", key: "1430ec127e097e1113259c5e1be1ba70" }), complete: function( res ) { wx.showToast({ title:'成功', icon:'success', duration:2000 }) that.setData( { red:'red', 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; } setTimeout(function(){ wx.hideToast() },2000) } }) }}) 依賴util.js代碼:
function json2Form(json) { var str = []; for(var p in json){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p])); } return str.join("&"); } module.exports = { formatTime: formatTime, json2Form:json2Form,}展示圖:

如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答