首页 > 代码库 > 微信小程序开发手记之六:API

微信小程序开发手记之六:API

准备工作


API中有关于网络的接口,需要配置合法域名,如果不想配置,可以直接在开发工具中设置,如下图
技术分享

如果没有在开发工具中设置,也没有设置合法域名,运行时爆出如下错误
技术分享

wx.request


该API既支持http请求,也支持https请求

对于网络请求,小程序大大减轻了我们的工作量,不需要再次解析json,只需要将data的结构设置的与返回的json即可。

Page({

    onl oad: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;
    margin-right: -9px;
    overflow: hidden;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

.image_pre{
    display: block;
    width: 150rpx;
    height: 150rpx;
}

.image_parent{
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
}

.weui-uploader__input {
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}

.weui-uploader__input-box {
  float: left;
  position: relative;
  margin-right: 9px;
  margin-bottom: 9px;
  width: 77px;
  height: 77px;
  border: 1px solid #D9D9D9;
}
.weui-uploader__input-box:before,
.weui-uploader__input-box:after {
  content: " ";
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  background-color: #D9D9D9;
}
.weui-uploader__input-box:before {
  width: 2px;
  height: 39.5px;
}
.weui-uploader__input-box:after {
  width: 39.5px;
  height: 2px;
}
.weui-uploader__input-box:active {
  border-color: #999999;
}
.weui-uploader__input-box:active:before,
.weui-uploader__input-box:active:after {
  background-color: #999999;
}

.weui-uploader__bd {
  margin-bottom: -4px;
  margin-right: -9px;
  overflow: hidden;
}

wx.startRecord,wx.stopRecord,wx.playVoice,wx.pauseVoice,wx.stopVoice


效果图如下:
技术分享

Page({

  data:{
    path:"path"
  },
  startRecord:function(e){

    var that = this
    wx.startRecord({
      success: function(res){
        // success
        console.log("start-success")
        that.setData({
          path:res.tempFilePath
        })
      },
      fail: function(res) {
        // fail
        console.log("start-fail")
      },
      complete: function(res) {
        // complete
      }
    })
  },
  stopRecord:function(e){

    wx.stopRecord({
      success: function(res){
        // success
        console.log("stop-success")
      },
      fail: function(res) {
        // fail
        console.log("stop-fail")
      },
      complete: function(res) {
        // complete
      }
    })
  },
  playVoice:function(e){

    wx.playVoice({
      filePath: this.data.path,
      success: function(res){
        // success
        console.log("play-success")
      },
      fail: function(res) {
        // fail
        console.log("play-fail")
      },
      complete: function(res) {
        // complete
      }
    })
  },
  pauseVoice:function(e){

    wx.pauseVoice({
      success: function(res){
        // success
        console.log("pause-success")
      },
      fail: function(res) {
        // fail
        console.log("pause-fail")
      },
      complete: function(res) {
        // complete
      }
    })
  },
  stopVoice:function(e){

    wx.stopVoice({
      success: function(res){
        // success
        console.log("stop-success")
      },
      fail: function(res) {
        // fail
        console.log("stop-fail")
      },
      complete: function(res) {
        // complete
      }
    })
  }


})
<view class="demo-view-5">
    <button class="bc_text" type="primary" bindtap="startRecord">开始录音</button>

    <button class="bc_text" type="primary" bindtap="stopRecord">录音结束</button>

    <button class="bc_text" type="primary" bindtap="playVoice">播放录音</button>

    <button class="bc_text" type="primary" bindtap="pauseVoice">暂停播放录音</button>

    <button class="bc_text" type="primary" bindtap="stopVoice">停止播放录音</button>


    <text class="bc_text">{{path}}</text>
</view>
.demo-view-5{
    display:block;
    height:1500rpx;
    flex-direction: column;
    background-color: #E8E8E8;
    margin-bottom: -4px;
    margin-right: -9px;
    overflow: hidden;
}
.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

wx.uploadFile


图片上传的方法如下


Page({

  data:{ 
    "src":"",
    "status": 0,
    "msg": "msg",
    "data": {
        "successCount":0 ,
        "urlList": []
    }
  },
  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({
          src:res.tempFilePaths[0]
        })
      },
      fail: function(res) {
        // fail
      },
      complete: function(res) {
        // complete
      }
    })

  },
  uploadImage:function(){

    var that = this
    wx.uploadFile({
      url: ‘http:...‘,
      filePath:this.data.src,
      name:‘collection‘,
      // header: {}, // 设置请求的 header
      // formData: {}, // HTTP 请求中其他额外的 form data
      success: function(res){
        // success
        var bean = JSON.parse(res.data)
        that.setData({
          "status":bean.status,
          "msg":bean.msg,
          "data":bean.data
        })
      },
      fail: function(res) {
        // fail
        console.log("upload-fail")
      },
      complete: function(res) {
        // complete

      }
    })
  }

})
<view class="demo-view-5">
    <button class="bc_text" type="primary" bindtap="choosePic">选择要上传的图片</button>
    <button class="bc_text" type="primary" bindtap="uploadImage">上传图片</button>
    <text class="bc_text">{{msg}}</text>
    <image src="{{data.urlList[0]}}" mode="aspectFill"></image>
</view>
.demo-view-5{
    display:block;
    height:1500rpx;
    flex-direction: column;
    background-color: #E8E8E8;
    margin-bottom: -4px;
    margin-right: -9px;
    overflow: hidden;
}
.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

踩坑记录

其中有一个很坑的地方,这个接口是我在app项目中找出来的,app上可以完美运行,解析json都没出问题,但在这里就出了问题,下面是上传成功的回调,如下

success: function(res){
        // success
        var bean = JSON.parse(res.data)
        that.setData({
          "status":bean.status,
          "msg":bean.msg,
          "data":bean.data
        })
      },

刚开始的时候,var bean = res.data,结果设置的status,msg,data值都是undefined,搞得有点怀疑人生。后来将res.data再解析一下,也就是写成:var bean = JSON.parse(res.data),这样就成功了。


文件下载的demo如下

效果图如下:
技术分享

Page({

  data:{
    src:"../../../image/cat.jpg",
    success:false
  },
  downloadVedio:function(){

    var that = this

    wx.downloadFile({
      url: "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1492582586&di=3c8a3277ee28b8d357176910e535ce6f&src=http://r001.joyme.com/r001/image/2012/07/81/5FB12B816020EFFB99A1AC6CD28A6C72.jpg",
      // type: ‘image‘, // 下载资源的类型,用于客户端识别处理,有效值:image/audio/video
      // header: {}, // 设置请求的 header
      success: function(res){
        // success
        console.log("success")
        that.setData({
          src:res.tempFilePath,
          success:true
        })
      },
      fail: function(res) {
        // fail
        console.log("fail")
      },
      complete: function(res) {
        // complete
      }
    })
  }


})
<view class="demo-view-5">
    <button class="bc_text" type="primary" bindtap="downloadVedio">下载图片</button>
    <text wx:if="{{success}}" class="bc_text">成功</text>
    <image src="{{src}}" ></image>
</view>
.demo-view-5{
    display:block;
    height:1500rpx;
    flex-direction: column;
    background-color: #E8E8E8;
    margin-bottom: -4px;
    margin-right: -9px;
    overflow: hidden;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

wx.getLocation,wx.openLocation


获取当前经纬度,并在地图中显示。在手机上显示的比较准,在开发工具上显示的偏离很大。

效果图如下
技术分享

Page({

  data:{
    latitude:"",
    longitude:""
  },
  getLocation:function(){

    var that = this
    wx.getLocation({
      type: ‘gcj02‘, // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
      success: function(res){
        // success

        that.setData({
          latitude:res.latitude,
          longitude:res.longitude
        })
      },
      fail: function(res) {
        // fail
      },
      complete: function(res) {
        // complete
      }
    })
  },
  openLocation:function(e){

    var that = this
    wx.openLocation({
      latitude: that.data.latitude, // 纬度,范围为-90~90,负数表示南纬
      longitude: that.data.longitude, // 经度,范围为-180~180,负数表示西经
      scale: 28, // 缩放比例
      // name: ‘name‘, // 位置名
      // address: ‘address‘, // 地址的详细说明
      success: function(res){
        // success
      },
      fail: function(res) {
        // fail
      },
      complete: function(res) {
        // complete
      }
    })
  }

})
<view class="demo-view-5">
    <button type="primary" class="bc_text" bindtap="getLocation">获取当前位置</button>
    <button type="primary" class="bc_text" bindtap="openLocation">显示当前位置</button>

</view>
.demo-view-5{
    display:block;
    height:1500rpx;
    flex-direction: column;
    background-color: #E8E8E8;
    margin-bottom: -4px;
    margin-right: -9px;
    overflow: hidden;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

wx.createMapContext如下


效果图如下
技术分享

Page({

  onReady:function(e){
    this.mapCtx = wx.createMapContext("wisely")
  },
  getCenterLocation:function(){
    this.mapCtx.getCenterLocation({
      success:function(res){
        console.log(res.longitude)
        console.log(res.latitude)
      }
    })
  },
  moveToLocation:function(){
    this.mapCtx.moveToLocation()
    console.log("move")
  }
})
<view class="demo-view-5">
    <map id="wisely" show-location style="width:750rpx;height:500rpx"/>

     <button type="primary" class="bc_text" bindtap="getCenterLocation">获取中心点位置</button>
    <button type="primary" class="bc_text" bindtap="moveToLocation">移动回原来位置</button>
</view>
.demo-view-5{
    display:flex;
    height:1500rpx;
    background-color: #E8E8E8;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

wx.chooseLocation


属性请看这里。

效果图如下:

技术分享

Page({
  chooseLocation:function(){

    wx.chooseLocation({
      success: function(res){
        // success
        console.log(res.name)
        console.log(res.address)
        console.log(res.longitude)
        console.log(res.latitude)
        console.log("-------------------------------")
      },
      fail: function(res) {
        // fail
      },
      complete: function(res) {
        // complete
      }
    })
  }
})
<view class="demo-view-5">
     <button type="primary" class="bc_text" bindtap="chooseLocation">选择位置</button>
</view>

从动图可以看出,第一次选中位置时,并没有打印语句,应该是失败了,第2次和第3次成功打印。

wx.scanCode


Page({

  scan:function(){

    wx.scanCode({
      success: function(res){
        // success
        wx.showToast({
          title:"success"
        })
      },
      fail: function(res) {
        // fail
        wx.showToast({
          title:"fail"
        })
      },
      complete: function(res) {
        // complete
      }
    })
  }
})
<view class="demo-view-5">
     <button type="primary" class="bc_text" bindtap="scan">点击扫码</button>
</view>

wx.showModal


效果图如下
技术分享

Page({

  showDialog:function(e){

    wx.showModal({
      title:‘title‘,
      content:‘content‘,
      showCancel:true,
      // cancelText:‘cancel‘,
      cancelColor:‘#0000FF‘,
      // confirmText:‘confirm‘,
      confirmColor:‘#FF0000‘,
      success:function(res){

        if(res.confirm){
          console.log("确定")
        } else if(res.cancel){
          console.log("取消")
        }
      }
    })
  }
})
<view class="demo-view-5">
     <button type="primary" class="bc_text" bindtap="showDialog">点击弹窗</button>
</view>
.demo-view-5{
    display:flex;
    height:1500rpx;
    background-color: #E8E8E8;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

踩坑记录

  1. cancelText,confirmText不能设置,一旦设置了其中某一个,窗口就不会弹出。
  2. res.cancel永远为false,所以只需要判断res.confirm是否为true即可

wx.showActionSheet


效果图如下
技术分享

Page({

  showActionSheet:function(e){

    wx.showActionSheet({
      itemList:[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘],
      itemColor:‘#FF0000‘,
      success:function(res){
        console.log(res.tapIndex)
        console.log(‘----success--‘)
      },
      fail:function(res){
        console.log("----"+res.errMsg)
        console.log(‘----fail--‘)
      }
    })
  }
})
<view class="demo-view-5">
     <button type="primary" class="bc_text" bindtap="showActionSheet">点击弹出列表</button>
</view>
.demo-view-5{
    display:flex;
    height:1500rpx;
    background-color: #E8E8E8;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

踩坑记录

细心看上面的动图就能发现,我在点击了“取消”之后,先运行了fail的方法,然后又运行了success的方法,这个应该是个bug。

wx.showLoading,wx.hideLoading


效果图如下
技术分享

Page({

  show:function(){
    wx.showLoading({
      title:‘正在加载‘,
      success:function(res){

      }
    })
  },
  hide:function(){

    wx.hideLoading()
  }

})
<view class="demo-view-5">
     <button type="primary" class="bc_text" bindtap="show">展示loading</button>
     <button type="primary" class="bc_text" bindtap="hide">隐藏loading</button>
</view>
.demo-view-5{
    display:flex;
    height:1500rpx;
    background-color: #E8E8E8;
}

.bc_text{
    margin: 20rpx;
    background-color: #FFFFFF;
    width:700rpx;
}

踩坑记录

这个API很有问题,在上面的图片中,当loading在前台时,还可以点击下面的按钮,隐藏掉它。这就意味着在loading显示时,还可以操作下面的组件,loading的作用貌似就没有了,毕竟它的一个作用就是防止用户点击下面的内容。

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    微信小程序开发手记之六:API