API的应用
网络API
微信小程序处理的数据通常从后台服务器获取,再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。微信原生AP接口或第三方APL提供了各类接口实现前后端交互
网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。微信开发团队提供了10个网络API接口
1.wx.request(0bject)接口 用于发起HTTPS 请求
2.wx.uploadFile(Object)接口 用于将本地资源上传到后台服务器
3.wx.downloadFile(Object)接口用于下载文件资源到本地
4.wx.connectSocket(0bject)接口用于创建一个WehSocket 连接
5.wx.sendSocketMessage(0bject)接口 用于实现通过 WehSocket连接发送数据
6.wx.closeSocket(0bject)接口用于关闭WebSocket 连接
7.wx.onSocketOpen(CallBack)接口用于监听WebSocket 连接打开事件
8.wx.onSocketEror(CallBack)接口用于监听WebSocket 错误
9.wx.onSocketMessage(CallBack)接口 用于实现监听WebSocket 接收到服务器的消息
事件
10.wx.onSocketClose(CallBack)接口用于实现监听WebSocket 关闭
发起网络请求
例如,通过 wx.requesl(0bject)获取百度(https:// www,baidu.com)首页的数据。(需要在微信公众平台小程序服务器配置中的request合法域名中添加“htps:// www.baidu.com”。)
<!--pages/baidu/baidu.wxml-->
<button type="primary" bind:tap="getbaidutap">获取HTML数据</button>
<textarea value="{{html}}" auto-height="" maxlength="0"></textarea>
// pages/baidu/baidu.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(Object)的GET方法获取邮政编码对应的地址信息。
<!--pages/postcode/postcode.wxml-->
<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder="6位邮政编码" />
<button type="primary" bindtap="fine">查询</button>
<block wx:for="{{address}}">
<block wx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>
// pages/postcode/postcode.js
Page({
data: {
postcode:'',
address:[],
errMsg:'',
erroe_code:-1
},
input:function(e){
this.setData({
postcode:e.detail.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:'',
erroe_code:res.data.error_code,
address:res.data.result.list
})
}
else {
self.setData({
errMsg:res.data.reason || res.data.reason,
erroe_code:res.data.error_code
})
}
}
})
}
}
})
上传文件
wx.uploadFile(Object) 接口用于将本地资源上传到开发者服务器, 并在客户端发起一个HTTPSPOST 请求
<!--pages/upload/upload.wxml-->
<button type="primary"bindtap="uploadimage">上传图片</button ><image src="/image/8.png"
mode="widthFix"/>
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.statusCodel=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();
}
})
}}
}
})
下载文件
wx.downloadFile(Objeet)接口用于实现从开发者服务器下载文件资源到本地,在客户端
直接发起一个HITPGET请求,返回文件的本地临时路径
<!--pages/downloadFile/downloadFile.wxml-->
<button type="primary" bind:tap="downloadimage">下载图像</button>
<image src="/image/8.png" mode="widthFix" style="width: 80%;height: 300px;"></image>
// pages/downloadFile/downloadFile.js
Page({
/**
* 页面的初始数据
*/
data: {
img:null
},
downloadimage:function(){
var that=this;
wx.downloadFile({
//通过WAMP软件实现
url: 'http://localhost/1.jpg',
success:function(res){
console.log(res)
that.setData({
img:res.tempFilePath
})
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
多媒体API
多媒体API主要包括图片API、录音API、音频播放控制API、音乐播放控制API等,其目的是丰富小程序的页面功能
图片API
选择图片或拍照
wx.chooseImage({
count:2,//默认值为9
sizeType:['original','compressed'],//可以指定是原图还是压缩图,默认者都有
sourceType:['album','camera'],//可以指定来源是相册还是相机,默认二者都有
success:function(res){
//返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性来显示图片
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.jpg"]
})
获取图片信息
wx.chooseImage({
success:function(res){
wx.getImageInfo({
src: res.tempFilePaths[0],
success:function(e){
console.log(e.width)
console.log(e.height)
}
})
},
})
保存图片到系统相册
录音API
开始录音
停止录音
wx.startRecord({
success:function(res){
var tempFilePath=tempFilePath
},
fail:function(res){
//录音失败
}
})
setTimeout(function(){
//结束录音
wx.stopRecord()},10000)
音频播放控制API
音频播放控制API主要用于对语音媒体文件的控制,包括播放、暂停、停止及audio组件的控制,主要包括以下3个API
1.wx.playVoice(Object)接口 用于实现开始播放语音
2.wx.pauseVoice(Object)接口用于实现暂停正在播放的语音
3. 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.playBackgroundAudio({
dataUrl: 'http://bmob-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3',
title:'有一天',
coverImgUrl:'http:///bmob-cdn-16488.b0.upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724.jpg',
success:function(res){
console.log(res)//成功返回playBackgroundAudio:ok
}
})
获取音乐播放状态
wx.getBackgroundAudioPlayerState({
success:function(res){
var status=res.status
var dataUrl=res.dataUrl
var currentPosition=res.currentPosition
var duration=res.duration
var downloadPercent=res.downloadPercent
console.log("播放状态:"+status)
console.log("音乐文件地址:"+dataUrl)
console.log("音乐文件当前播放位置:"+currentPosition)
console.log("音乐文件的长度:"+duration)
console.log("音乐文件的下载进度:"+downloadPercent)
}
})
控制音乐播放进度
wx.seekBackgroundAudio({
position: 30,
})
暂停播放音乐
wx.playBackgroundAudio({
dataUrl: '/music/a.mp3',
title:'我的音乐',
coverImgUrl:'images/poster.jpg',
success:function(){
console.log('开始播放音乐了');
}
});
setTimeout(function(){
console.log('暂停播放');
wx.stopBackgroundAudio();
},5000);//5秒后自动停止
停止播放音乐
wx.playBackgroundAudio({
dataUrl: '/music/a.mp3',
title:'我的音乐',
coverImgUrl:'images/poster.jpg',
success:function(){
console.log('开始播放音乐了');
}
});
setTimeout(function(){
console.log('暂停播放');
wx.stopBackgroundAudio();
},5000);//5秒后自动停止
监听音乐播放
wx.playBackgroundAudio({
dataUrl: this.data.musicData.dataUrl,
title:this.data.musicData.title,
coverImgUrl:this.data.musicData.coverImgUrl,
success:function(){
wx.onBackgroundAudioStop(function(){
that.setData({
isplayingMusic:false
})
})
}
})
监听音乐暂停
监听音乐停止
示例
<!--pages/music/music.wxml-->
<view class="container">
<image class="bgaudio"src = "{{changedImg? music.coverImg:'/image/8.png'}}"/>
<view class ="control-view">
<!--使用data-how定义一个0表示快退10秒-->
<image src ="/image/1.jpg"bindtap="onPositionTap"data-how= "0 "/>
<image src = "/image/2.jpg" bindtap = "onAudioTap"/>
<image src ="/image/3.jpg"bindtap = "onStopTap"/><!--使用data-how定义一个1表示快进10秒-->
<image src ="/image/3.jpg"bindtap ="onPositionTap"data-how = "1"/>
</view >
</view >
/* pages/music/music.wxss */
.bgaudio{
height:350rpx; width:350rpx;
margin-bottom:100rpx;
}
.control-view image{
height:64rpx;
width:64rpx;
margin:30rpx;
}
Page({
data:{
//记录播放状态
isPlaying:false,
//记录coverImg,仅当音乐初始时和播放停止时,使用默认的图片。播放中和暂停时,都使用当前音乐的图片
coverImgchangedImg:false,
//音乐内容
music:{
"url":"../images/e e.mp4",
"title":"盛晓玫-有一天",
"coverImg":
"../images/e e.mp4"
},
},
onLoad:function(){
//页面加载时,注册监听事件
this.onAudioState();
},
//点击播放或者暂停按钮时触发
onAudioTap:function(event){
if(this.data.isPlaying){
//如果在正常播放状态,就暂停,并修改播放的状态
wx.pauseBackgroundAudio();
}else{
//如果在暂停状态,就开始播放,并修改播放的状态28
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(){
//改变coverImg和播放状态
that.setData({ isPlaying:false,changedImg:false});
}
})
},
//点击“快进10秒”或者“快退10秒”时,触发
onPositionTap:function(event){
let how = event.target.dataset.how;//获取音乐的播放状态
wx.getBackgroundAudioPlayerState({
success:function(res){
//仅在音乐播放中,快进和快退才生效
//音乐的播放状态,1表示播放中54
let status = res.status;
if(status === 1){//音乐的总时长
let duration = res.duration;//音乐播放的当前位置
let currentPosition = res.currentPosition;
if(how ==="0"){
//注意:快退时,当前播放位置快退10秒小于0时,直接设置position为1;否则,直接减去10秒//快退到达的位置
let position = currentPosition - 10;
if(position <0){
position =1;//执行快退
}
wx.seekBackgroundAudio({
position: position
});
//给出一个友情提示,在实际应用中,请删除!!!
wx. showToast({title:"快退10s",duration:500});
}
if(how === "1"){//注意:快进时,当前播放位置快进10秒后大于总时长时,直接设置position 为总时长减1
//快进到达的位置
let position =currentPosition +10;
if(position >duration){
position =duration-1;//执行快进
}
wx.seekBackgroundAudio({
position: position});//给出一个友情提示,在实际应用中,请删除!!!
wx.showToast({ title:"快进10s",duration:500});
}
}else { //给出一个友情提示,在实际应用中,请删除!!!
wx.showToast({title:"音乐未播放",duration:800});
}
}
})
},//音乐播放状态
onAudioState:function(){
let that =this;
wx.onBackgroundAudioPlay(function(){//当wx.playBackgroundAudio()执行时触发101 //改变coverImg和播放状态
that.setData({ isPlaying:true,changedImg:true});
console.log("on play");
});
wx.onBackgroundAudioPause(function(){ //当wx.pauseBackgroundAudio()执行时触发//仅改变播放状态
that.setData({isPlaying:false});
console.log("on pause");
});
wx.onBackgroundAudioStop(function(){ //当音乐自行播放结束时触发//改变coverImg和播放状态
that.setData({isPlaying:false,changedImg:false});
console.log("on stop");
});
}
})
{
}
文件API
从网络上下载或录音的文件都是临时保存的,若要持久保存,需要用到文件API。文件API提供了打开、保存、删除等操作本地文件的能力,主要包括以下5个API接口
wx.saveFile(Object)接口 用于保存文件到本地
wx.getSavedFileList(Object)接口 用于获取本地已保存的文件列表
wx.getSaveFileInfo(Object)接口 用于获取本地文件的文件信息
wx.removeSaveFile(Object)接口 用于删除本地存储的文件
wx.openDocument(Object)接口 用于新开页面打开文档支持格式:doc、xls、ppt、pdf、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.saveFilePath;
console.log(saveFilePath)
}
})
}
})
})
获取本地文件列表
//js
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.saveFilePath;
wx.getSavedFileInfo({
filePath:saveFilePath,
success:function(res){
console.log(res.size)
}
})
}
})
}
})
删除本地文件
//js
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(0bject)接口将数据存储到本地缓存接口指定的key中,接口执行后会覆盖原来key 对应的内容
// 保存数据 同步 js文件
wx.setStorageSync('age', '25')
wx.setStorage({
key:'name',
data:'sdy',
success:function(res){
console.log(res)
}
})
wx. setStorageSync(key,data)是同步接口,其参数只有 key 和 data
wx.setStorageSync('age', '25')
获取数据
wx.getStorage(0bject)接口是从本地缓存中异步获取指定key对应的内容
wx.getStorage({
key:'name',
success:function(res){
console.log(res.data)
},
})
wx.gelStorageSyne(key)从本地缓存中同步获取指定key 对应的内容。其参数只有key
try{
var value=wx.getStorageSync('age')
if(value){
console.log("获取成功"+value)
}
}catch(e){
console.log("获取失败")
}
删除数据
wx.removeStorage(0bject)接口用于从本地缓存中异步移除指定key
wx.removeStorage({
key: 'name',
success:function(res){
console.log("删除成功")
},
fail:function(){
console.log("删除失败")
}
})
wx.removeStorageSyne(key)接口用于从本地缓存中同步删除指定key对应的内容。其参数只有key
try{
wx.removeStorageSync('name')
}catch(e){
//Do something when catch error
},
清空数据
wx.clearStorage()接口用于异步清理本地数据缓存,没有参数
wx.getStorage({
key:'name',
success:function(res){
//清理本地数据缓存
wx.clearStorage()
}
})
wx.clearStroageSyne()接口用于同步清理本地数据缓存
try{
wx.clearStorageSync()
}catch(e){}
位置信息API
wx.getLocation(Object)接口用于获取位置信息
wx.chooseLocation(Object)接口用于选择位置信息
wx.openLocation(Object)接口用于通过地图显示位置
获取位置信息
wx.getLocation(Object)接口
wx.getLocation(Object)
wx.getLocation({
type:'wgs84',
success:function(res){
console.log("经度:"+res.longitude);
console.log("纬度"+res.latitude);
console.log("速度"+res.longitude);
console.log("位置的精确度" +res.accuracy);
console.log("水平精确度"+res.horizontalAccuracy);
console.log("垂直精确度"+res.verticalAccuracy);
},
})
选择位置信息
wx.chooseLocation(Object)接口用于在打开的地图中选择位置,用户选择位置后可返回当前位置的名称、地址、经纬度信息
wx.chooseLocation(Object)调用成功后,返回的参数如下表所示
wx.chooseLocation({
success:function(res){
console.log("位置的名称"+res.name)
console.log("位置的地址"+res.address)
console.log("位置的经度"+res.longitude)
console.log("位置的纬度"+res.latitude)
}
})
显示位置信息
wx.getLocation({
type:'gcj02',//返回可以用于wx.openLocation的经纬度
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.getSystemInfoSync()接口 用于获取系统信息。
wx.getNetworkType(Object)接口 用于获取网络类型。
wx.onNetworkStatusChange(CallBack)接口 用于监测网络状态改变。
wx.makePhoneCall(Object)接口 用于拨打电话。
wx.scanCode(Object)接口 用于扫描二维码
获取系统信息
wx. getSystemInfo(Object)接口、wx. getSystemInfoSync()接口分别用于异步和同步获取系统信息
wx. getSystemInfo()接口或wx.getSystemInfoSync()接口调用成功后,返回系统相关信息
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. getNetworkType()接口被成功调用,则返回网络类型包,有wifi、2G、3G、4G、unknown(Android下不常见的网络类型)、none(无网络)
wx.getNetworkType({
success:function(res){
console.log(res.networkType)
},
})
监听网络状态变换
wx. onNetworkStatusChange(CallBack)接口用于监听网络状态变化,当网络状态变化时,返回当前网络状态类型及是否有网络连接
wx.onNetworkStatusChange(function(res){
console.log("网络是否连接:"+res.isConnected)
console.log("变化后的网络类型:"+res.networkType)
})
拨打电话
wx. makePhoneCall(Object)接口用于实现调用手机拨打电话
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)
}
})