微信网络请求方法跟大多数网络请求基本一致,比较简单。
实现案例:
视图层,两个简单的按钮,一个文本框用于显示请求回来的数据
<view class="page">
<button type="primary"class="twobutton" bindtap="getRequest"> GET请求</button>
<button type="primary" class="twobutton" bindtap="postRequest"> POST请求</button>
<view class="twobutton"><text >{{returnData}}</text></view>
</view>
控制层,分别实现get请求和post请求的方法
//获取应用实例
var app = getApp()
Page({
data: {
returnData: "",
},
onLoad: function(options) {
this.setData({
//上一页面带过来的数据
returnData: options.title
})
} ,
//get请求
getRequest: function (e) {
var that = this;
wx.request({
url: "http://www.weather.com.cn/data/sk/101190408.html",
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function (res) {
// success
console.log(res);
that.setData({ returnData: res.data.weatherinfo.city });
},
fail: function () {
// fail
wx.showToast({
title: "网络异常,稍后再试。"
});
}
})
},
//post请求
postRequest: function (e) {
// wx.showToast({
// title: "post请求"
// });
var that = this;
wx.request({
url: 'http://op.juhe.cn/onebox/weather/query',
data: { cityname: "上海", key: "1430ec127e097e1113259c5e1be1ba70" },
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: { "Content-Type": "application/x-www-form-urlencoded" }, // 设置请求的 header
success: function (res) {
// success
console.log(res);
that.setData({returnData:res.data.reason});
},
fail: function () {
// fail
wx.showToast({
title: "网络异常,稍后再试。"
});
},
})
}
})