第六章总结

 网络API

发起网络请求

wx.request(0bject)接口 用于发起HTTPS 请求
wx.uploadFile(0bject)接口 用于将本地资源上传到后台服务器
wx.downloadFile(0bject)接口 用于下载文件资源到本地
wx.connectSocket(0bject)接口用于创建一个WebSocket 连接
wx.sendSocketMessage(0bject)接口 用于实现通过WebSocket 连接发送数据
wx.closeSocket(0bject)接口 用于关闭 WebSocket 连接
wx.onSocketOpen(CallBack)接口用于监听WebSocket 连接打开事件
wx.onSocketError(CallBack)接口 用于监听 WebSocket 错误
wx.onSocketMessage(CallBack)接口用于实现监听WebSocket接收到服务器的消息
事件
wx.onSocketClose(CallBack)接口 用于实现监听WebSocket 关闭

通过wx.request获取百度首页数据
<button type="primary"bindtap="getbaidutap">获取HTML数据</button>
<textarea value='{{html}}'auto-heightmaxlength='0'></textarea>
//js
Page({
  data:{
    html:""
  },
  getbaidutap:function(){
    var that=this;
    wx.request({
      url:'https://www.baidu.com',
      data:{},
      header:{'Content-Type':'application/json'},
      success:function(res){
        console.log(res);
        that.setData({
          html:res.data
        })
      }
    })
  }
})

 

  通过wx.request的GET方法获取邮政编码对应地址信息
<view>邮政编码:</view>
<input type="text"bindinput="input"placeholder='6位邮政编码'/>
<button type="primary"bindtap="find">查询</button>
<block kwx:for="{{address}}">
<text>{{item}}</text>
</block>
//js
Page({
  data:{
    postcode:"",
    address:[],
    errMsg:"",
    error_code:-1
  },
  input:function(e){
    this.setData({
      postcode:e.datail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.data.postcode;
    if(postcode!=null&&postcode!=""){
      var self=this;
      wx.showToast({
        title: '正在查询,请稍后......',
        icon:'loading',
        duration:10000
      });
      wx.request({
        url:'https://v.juhe.cn/postcode/query',
        data:{
          'postcode':postcode,
          'key':'0ff9bfccdf147476e067de994eb5496e'
        },
        header:{
          'Content-Type':'application/json',
        },
        method:'GET',
        success:function(res){
          wx.hideToast();
          if(res.data.error_code==0){
            console.log(res);
          self.setData({
            errMsg:"",
            error_code:res.data.error_code,
            address:res.data.result.list
          })
        }
       else{
          self.setData({
            errMsg:res.data.reason || res.data.reason,
            error_code:res.data.error_code
          })
        }
      }
      })
    }
  }
})
 通过wx.request的POST方法获取邮政编码对应地址信息
<view>邮政编码:</view>
<input type="text"bindinput="input"placeholder='6位邮政编码'/>
<button type="primary"bindtap="find">查询</button>
<block kwx:for="{{address}}">
<block kwx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>
//js
Page({
  data:{
    postcode:"",
    address:[],
    errMsg:"",
    error_code:-1
  },
  input:function(e){
    this.setData({
      postcode:e.datail.value,
    })
    console.log(e.detail.value)
  },
  find:function(){
    var postcode=this.data.postcode;
    if(postcode!=null&&postcode!=""){
      var self=this;
      wx.showToast({
        title: '正在查询,请稍后......',
        icon:'loading',
        duration:10000
      });
      wx.request({
        url:'https://v.juhe.cn/postcode/query',
        data:{
          'postcode':postcode,
          'key':'0ff9bfccdf147476e067de994eb5496e'
        },
        header:{
          'Content-Type':'application/X-www-form-urlencoded'
        },
        method:'POST',
        success:function(res){
          wx.hideToast();
          if(res.data.error_code==0){
            console.log(res);
          self.setData({
            errMsg:"",
            error_code:res.data.error_code,
            address:res.data.result.list
          })
        }
       else{
          self.setData({
            errMsg:res.data.reason || res.data.reason,
            error_code:res.data.error_code
          })
        }
      }
      })
    }
  }
})

上传文件 

  通过wx.uploadFile将图片上传到服务器
<button type="primary" bindtap="uploadimage">上传图片</button>
<image src="{{img}}" mode="widthFix"/>
//js
Page({
  data:{
    img:null,
  },
  uploadimage:function(){
    var that=this;
    wx.chooseImage({
      success:function(res){
        var tempFilePaths=res.tempFilePaths
        upload(that.tempFilePaths);
      }
    })
    function upload(page,path){
      wx.showToast({
        icon:"loading",
        title: '正在上传',
      }),
      wx.uploadFile({
        url:"http://localhost/",
        filePath: 'path[0]',
        name: 'file',
        success:function(res){
          console.log(res);
          if(res.statusCode!=200){
            wx.showModal({
                title: '提示',
                content: '上传失败',
                showCancel:false
            })
            return;
          }
          var data=res.data
          page.setData({
            img:path[0]
          })
        },
        fail:function(e){
          console.log(e);
          wx.showModal({
            title:'提示',
            content: '上传失败',
            showCancel:false
          })
        },
        complete:function(){
          wx.hideToast();
        }
      })
    }
  }
})

下载文件

<button type="primary" bindtap='downloadimage'>下载图片</button>
<image src="{{img}}" mode="widthFix" style="width: 90%;height: 500px;"></image>
//js
Page({
  data:{
    img:null
  },
  downloadimage:function(){
    var that=this;
    wx.downloadFile({
      url: 'http://localhost/1.jpg',
      success:function(res){
        console.log(res)
        that.setData({
          img:res.tempFilePath
        })
      }
    })
  }
})

 多媒体API

图片API

wx.chooselmage(Object)接口 用于从本地相册选择图片或使用相机拍照。
wx.previewImage(Object)接口 用于预览图片。
wx.getlmageInfo(Object)接口 用于获取图片信息。
wx.savelmageToPhotosAlbum(Object)接口 用于保存图片到系统相册

选择图片或拍照

wx.chooseImage({
  count:2,
  sizeType:['original','compressed'],
  sourceType:['album','camera'],
  success:function(res){
    var tempFilePaths=res.tempFilePaths
    var tempFiles=res.tempFiles;
    console.log(tempFilePaths)
    console.log(tempFiles)
  }
})
预览图片

wx.previewImage({
  current:"http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
  urls: ["http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/1.png",
  "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
  "http://bmob-cdn-16488.b0.upaiyun.com/2018/02/05/3.png"]
})
 获取图片信息
wx.chooseImage({
  success:function(res){
    wx.getImageInfo({
      src: 'res.tempFilePaths[0],',
      success:function(e){
        console.log(e.width)
        console.log(e.height)
      }
    })
  }
})
 保存图片到系统相册

wx.chooseImage({
  success:function(res){
    wx.saveImageToPhotosAlbum({
      filePath: 'res.tempFilePaths[0]',
      success:function(e){
        console.log(e)
      }
    })
  }
})

 录音API

wx.startRecord(0bject)接口 用于实现开始录音。
wx.stopRecord(0bject)接口用于实现主动调用停止录音

开始录音

 停止录音
wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
  },
  fail:function(res){
  }
})
srtTImeout(function(){
  wx.stopRecord()
},10000)

 音频播放控制API

wx.playVoice(0bject)接口 用于实现开始播放语音
wx.pauseVoice(0bject)接口用于实现暂停正在播放的语音
wx.stopVoice(Object)接口 用于结束播放语音。

播放语音

wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath: 'tempFilePath',
      complete:function(){
      }
    })
  }
})
 暂停播放
wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath: 'tempFilePath'
    })
    setTimeout(function(){
      wx.pauseVoice()
    },5000)
  }
})
 结束播放
wx.startRecord({
  success:function(res){
    var tempFilePath=res.tempFilePath
    wx.playVoice({
      filePath: 'tempFilePath'
    })
    setTimeout(function(){
      wx.stopVoice()
    },5000)
  }
})

 音乐播放控制API

wx.playBackgrundAudio(0bject)接口用于播放音乐
wx.getBackgroundAudioPlayerState(0bject)接口 用于获取音乐播放状态
wx.seekBackgroundAudio(0bject)接口 用于定位音乐播放进度
wx.pauseBackgroundAudio()接口用于实现暂停播放音乐
wx.stopBackgroundAudio()接口 用于实现停止播放音乐
wx.onBackgroundAudioPlay(CallBack)接口 用于实现监听音乐播放
wx.onBackgroundAudioPause(CallBack)接口 用于实现监听音乐暂停
wx.onBackgroundAudioStop(CallBack)接口 用于实现监听音乐停止

<view class="container">
<image class="bgaudio" src="{{changedImg? music.coverImg:'/image/qyc.jpg'}}"/>
<view class="control-view">
<image src="/image/qyc.jpg"bindtap="onPositionTap"data-how="0"/>
<image src="/image/{{isPlaying?'pause':'qyc'}}.jpg"bindtap="onAudioTap"/>
<image src="/image/qyc.jpg"bindtap="onStopTOP"/>
<image src="/image/qyc.jpg"bindtap="onPositionTap"data-how="1"/>
</view>
</view>
//wxss
.bgaudio{
  height: 350rpx;
  width: 350rpx;
  margin-bottom: 100rpx;
}
.control-view image{
  height: 64rpx;
  width: 64rpx;
  margin: 30rpx;
}
//js
Page({
  data:{
    isPlaying:false,
    coverImgchangedImg:false,
    music:{
      "url":"http://bmob-cnd-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3",
      "title":"盛晓玫-有一天",
      "coverImg":
      "http://bomb-cnd-16488.b0.upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724.jpg"
    },
  },
  onLoad:function(){
    this.onAudioState();
  },
  onAudioTap:function(event){
    if(this.data.isPlaying){
      wx.pauseBackgroundAudio();
    }else{
      let music=this.data.music;
      wx.playBackgroundAudio({
        dataUrl: music.url,
        title:music.title,
        coverImgUrl:music.coverImg
      })
    }
  },
  onStopTap:function(){
    let that=this;
    wx.stopBackgroundAudio({
      success:function(){
        that.setData({isPlaying:false,changedImg:false});
      }
    })
  },
  onPositionTap:function(event){
    let how=event.target.datase.how;
    wx.getBackgroundAudioPlayerState({
      success:function(res){
        let status=res.status;
        if(status===1){
          let duration=res.duration;
          let currentPosition=res.currentPosition;
          if(how==="0"){
            let position=currentPosition-10;
            if(position<0){
              position=1;
            }
            wx.seekBackgroundAudio({
              position: position,
            });
            wx.showToast({title:"快退10s",duration:500});
          }
          if(how==="1"){
            let position=currentPosition+10;
            if(position>duration){
              position=duration-1;
            }
            wx.seekBackgroundAudio({
              position: position,
            });
            wx.showToast({title: "音乐未播放",duration:500});
             }
          }else{
            wx.showToast({title: "音乐未播放",duration:800});
          }
      }
    })
  },
  onAudioState:function(){
    let that=this;
    wx.onBackgroundAudioPlay(function(){
      that.setData({isPlaying:true,changedImage:ture});
      con

 

文件API

wx.saveFile(0bject)接口 用于保存文件到本地
wx.getSavedFileList(0bject)接口 用于获取本地已保存的文件列表
wx.getSaveFilelnfo(0bject)接口 用于获取本地文件的文件信息
wx.removeSaveFile(0bject)接口 用于删除本地存储的文件
wx openDocument(0bject)接口 用于新开页面打开文档,支持格式:doc、xls、pdf、ppt、docx、xlsx、ppts

保存文件

saveImg:function(){
  wx.chooseImage({
    count:1,
    sizeType:['original','compressed'],
    sourceType:['album','camera'],
    success:function(res){
      var tempFilePaths=res.tempFilePaths[0]
      wx.saveFile({
        tempFilePath:tempFilePaths,
        success:function(res){
          var saveFilePath=res.savedFilePath;
          console.log(saveFilePath)
        }
      })
    }
  })
}
 获取本地文件列表

wx.getSavedFileList({
  success:function(res){
    that.setData({
      fileList:res.fileList
    })
  }
})
 获取本地文件的文件信息

wx.chooseImage({
  count:1,
  sizeType:['original','compressed'],
  sourceType:['album','camera'],
  success:function(res){
    var tempFilePaths=res.tempFilePaths[0]
    wx.saveFile({
      tempFilePath:tempFilePaths,
      success:function(res){
        var saveFilePath=res.savedFilePath;
        wx.getSavedFileInfo({
          filePath:saveFilePath,
          success:function(res){
            console.log(res.size)
          }
        })
      }
    })
  }
})
删除本地文件 

wx.getSavedFileList({
  success:function(res){
    if(res.fileList.length>0){
      wx.removeSavedFile({
        filePath:res.fileList[0].filePath,
        complete:function(res){
          console.log(res)
        }
      })
    }
  }
})
 打开文档

wx.downloadFile({
  url:"http://localhost/fm2.pdf",
  success:function(res){
    var tempFilePath=res.tempFilePath;
    wx.openDocument({
      filePath:tempFilePath,
      success:function(res){
        console.log("打开成功")
      }
    })
  }
})

本地数据及缓存API        

保存数据

 wx.setStorage(object)接口将数据存储到本地缓存接口指定的key中,接口执行后会覆盖原来的key对应的内容

wx.setStorage({
  key:'name',
  data:'sdy',
  success:function(res){
    console.log(res)
  }
})

 wx.setStorageSync(key,data)是同步接口,其参数只有key和data。

wx.setStorageSync('age', '25')
获取数据

wx.getStorage(Object)接口是从本地缓存中异步获取指定key对应的内容。

wx.getStorage({
  key:'name',
  success:function(res){
    console.log(res.data)
  },
})

 wx.getStorageSync(key)从本地缓存中同步获取指令key对应内容。

try{
  var value=wx.getStorageSync('age')
  if(value){
    console.log("获取成功"+value)
  }
}catch(e){
  console.log("获取失败")
}
删除数据

wx.removeStorage(Object)接口用于从本地缓存中异步移除指定key。

wx.removeStorage({
  key: 'name',
  success:function(res){
    console.log("删除成功")
  },
  fail:function(){
    console.log("删除失败")
  }
})

wx.removeStorageSync(key)接口用于从本地缓存中同步删除指定key对应的内容。

try{
  wx.removeStorageSync('name')
}catch(e){
  
}
清空数据

wx.clearStorage()接口用于异步清理本地数据缓存,没有参数。

wx.getStorage({
key:'name',
successs:function(res){
wx.clearStorage()
},
})

wx.clearStorageSync()接口用于同步清理本地数据缓存。

try{
wx.clearStorageSync()
}catch(e){
}

位置信息API

小程序可以通过位置信息AP1来获取或显示本地位置信息,小程序支持WCS84和CC0标准,WGS84标准为地球坐标系,是国际上通用的坐标系;CCj02标准是中国国家测绘局定的地理信息系统的坐标系统,是由WGS84坐标系经加密后的坐标系,又称为火星坐标系默认为 WGS84 标准,若要查看位置需要使用GCj02标准。主要包括以下3个AP接口,

wx.getLocation(Objeet)接口用于获取位置信息。

wx.chooseLocation(Objeet)接口用于选择位置信息。

wx.openLocation(0bjeet)接口用于通过地图显示位置。

获取位置信息

wx.getLocation(0bject)接口用于获取当前用户的地理位置、速度,需要用户开启定位功能,当用户离开小程序后,无法获取当前的地理位置及速度,当用户点击“显示在聊天顶部时、可以获取到定位信息。

wx.getLocation({
type:'wgs84',
success:function(res)
console.1og("经度:"+res.longitude);
console.log("纬度:"+res.latitude);
console.1og("速度:"+res.longitude);
console.1og("位置的精确度:"+res.accuracy);
console.1og("水平精确度:"+res.horizontalAccuracy);
console.1og("垂直精确度:"+res.verticalAccuracy);
},
})
 选择位置信息

wx.chooseLocation(Object)接口用于在打开的地图中选择位置,用户选择位置后可返回当前位置的名称,地址,经维度信息。

wx.chooseLocation(
success:function(res)
console.log("位置的名称:"+res.name)console.l0g("位置的地址:"+res.address)
console.log("位置的经度:"+ res.longitude)
console.log("位置的纬度:"+res.latitude)
}
})
显示位置信息

wx.openLocation(Object)接口用于在微信内置地图中显示位置信息。

wx.getLocation({
type:'gcj02',
success:function(res){
var latitude =res.latitude
var longitude =res.longitude
wx.openLocation(
latitude: latitude,
longitude:longitude,
scale:10,
name:'智慧国际酒店'
address:'西安市长安区西长安区300号'
})
}
})

设备相关API

设备相关的接口用于获取设备相关信息,主要包括系统信息、网络状态、拨打电话及扫码等。主要包括以下5个接口 API:
wx.getSystemInfo(Object)接口、wx.getSystemInfoSyne()接口 用于获取系统信息wx.getNetworkType(Object)接口 用于获取网络类型
wx.onNetworkStatusChange(CallBack)接口用于监测网络状态改变
wx.makePhoneCall(Object)接口 用于拨打电话
wx.scanCode(Object)接口用于扫描二维码

获取系统信息

wx. getSystemInfo(0bject)接口、wx.getSystemInfoSync()接口分别用于异步和同步获取系统信息。

 wx.getSystemInfo()接口或wx.getSystemInfoSyne()接口调用成功后,返回系统相关信息

wx.getSystemInfo({
success:function(res){
console.log("手机型号:"+res.model)
console.log("设备像素比:"+res.pixelRatio)
console.log("窗口宽度:"+res.windowWidth)
console.log("窗口高度:"+res.windowHeight)
console.log("微信版本号:"+res.version)
console.log("操作系统版本:"+res.system)
console.log("客户端平台:"+res.platform)
},
})
 网络状态
获取网络状态

wx.getNetworkType(Object)用于获取网络类型

wx.getNextworkType({
success:function(res){
console.log(res.networkType)
},
})
监听网络状态变化

wx.onNetworkStatusChange(CallBack)用于监听网络变化,当网咯状态变化时,返回当前状态类型及是否有网络连接

wx.onNextworkStatusChange(function(res){
console.log("网络是否连接:"+res.isConnected)
console.log("变化后的网络类型:"+res.networkType)
})

拨打电话

wx.makePhoneCall({
phoneNumber:'18092585093'
})
扫描二维码

wx.scanCode(Object)接口用于调起客户端扫码界面,扫码成功后返回相应内容

 扫码成功后返回数据如下

//允许从照相机和相册扫码
wx.scanCode({
success:(res)=>{
console.log(res.result)
console.log(res.scantype)
console.log(res.charSet)
console.log(res.path)
}
})
//只允许从相机扫码
wx.scanCode({
onlyFromCamera:true,
success:(res)=>{
console.log(res)
}
})

 本章小结

本章主要介绍了小程序的各类核心API,包括网络API、多媒体API、文件API、本地数据及缓存API、位置信息API及设备相关API等。 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值