微信小程序 POST请求的实例详解
在微信小程序里post请求和get情求,写法差不多,但是还是有一点点不同的,下面利用post请求做一个查询天气的微信小程序demo。
页面代码:
<view> {{title}} </view>
<span ><!--index.wxml-->
<view class="container">
<view >{{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,
}
展示图:
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。