微信小程序 POST請求的實例詳解
更新時間:2017年09月29日 11:52:12 作者:king-w
這篇文章主要介紹了 微信小程序 POST請求的實例詳解的相關資料,希望通過本文能幫助到大家,需要的朋友可以參考下
微信小程序 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( '網(wǎng)絡請求失敗' ); 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, }
展示圖:
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
微信小程序實現(xiàn)給循環(huán)列表添加點擊樣式實例
這篇文章主要介紹了微信小程序實現(xiàn)給循環(huán)列表添加點擊樣式實例的相關資料,需要的朋友可以參考下2017-04-04Intersection?Observer交叉觀察器示例解析
這篇文章主要為大家介紹了Intersection?Observer交叉觀察器示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02