准备工作
API中有关于网络的接口,需要配置合法域名,如果不想配置,可以直接在开发工具中设置,如下图
如果没有在开发工具中设置,也没有设置合法域名,运行时爆出如下错误
wx.request
该API既支持http请求,也支持https请求。
对于网络请求,小程序大大减轻了我们的工作量,不需要再次解析json,只需要将data的结构设置的与返回的json即可。
Page({
onLoad:function(e){
var that = this
wx.request({
url: 'http://web.juhe.cn:8080/environment/air/cityair?city=beijing&key=.....自己的key....',
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function(res){
// success
console.log("statusCode:"+res.statusCode);
var dataBean = res.data
console.log("success",dataBean.resultcode)
console.log("success",dataBean.reason)
that.setData({
"resultcode":dataBean.resultcode,
"reason":dataBean.reason,
"error_code":dataBean.error_code,
"result":dataBean.result
})
},
fail: function(res) {
// fail
console.log("faile")
},
complete: function(res) {
// complete
console.log("complete")
}
})
},
data:{
"resultcode":"",
"reason":"",
"error_code":0,
"result":[
{
"citynow":{
"city":"",
"AQI":"",
"quality":"",
"date":""
},
"lastTwoWeeks":{
"1":{
"city":"",
"AQI":"",
"quality":"",
"date":""
}
}
}
]
}
})
<view>
<text>{
{result[0].citynow.quality}}</text>
</view>
wx.chooseImage,wx.previewImage和wx.getImageInfo
先看效果图
Page({
data:{
paths:[]
},
choosePic:function(){
var that = this
wx.chooseImage({
count: 9, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function(res){
// success
that.setData({
paths:res.tempFilePaths
})
},
fail: function(res) {
// fail
},
complete: function(res) {
// complete
}
})
},
prePic:function(e){
wx.previewImage({
// current: 'String', // 当前显示图片的链接,不填则默认为 urls 的第一张
urls: this.data.paths,
success: function(res){
// success
},
fail: function(res) {
// fail
},
complete: function(res) {
// complete
}
})
},
getImageInfo:function(e){
var path = this.data.paths[0]
wx.getImageInfo({
src: path,
success: function(res){
// success
console.log(res.width)
console.log(res.height)
console.log(res.path)
wx.showToast({
title:res.width+"*"+res.height
})
},
fail: function(res) {
// fail
wx.showToast({
title:'faile'
})
},
complete: function(res) {
// complete
// wx.showToast({//成功,失败与完成的showtoast不能同时设置,否则complete中的会冲掉前面设置的。
// title:'complete'
// })
}
})
}
})
<view class="demo-view-5">
<button class="bc_text" type="primary" bindtap="choosePic">选择图片</button>
<button class="bc_text" type="primary" bindtap="prePic">预览图片</button>
<button class="bc_text" type="primary" bindtap="getImageInfo">获取图片信息</button>
<view class="weui-uploader__bd" style="margin-left: 25rpx;">
<block wx:for="{
{paths}}">
<view class="image_parent">
<image src="{
{item}}" class="image_pre" mode="aspectFill"></image>
</view>
</block>
<view class="weui-uploader__input-box">
<view class="weui-uploader__input" bindtap="choosePic"></view>
</view>
</view>
</view>
.demo-view-5{
display:block;
height:1500rpx;
flex-direction: column;
background-color: #E8E8E8;
margin-bottom: -4px;