网络API
微信小程序处理的数据通常从后台服务器获取,再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。微信原生API接口或第三方API提供了各类接口实现前后端交互。
网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。微信开发团队提供了10个网络API接口
wx.request(Object)接口 用于发起HTTPS请求。
■ wx.uploadFile(Object)接口用于将本地资源上传到后台服务器。
■ wx.downloadFile(Object)接口用于下载文件资源到本地。
■ wx.connectSocket(Object)接口 用于创建一个WebSocket连接。
■ wx.sendSocketMessage(Object)接口 用于实现通过WebSocket连接发送数据。
■ wx.closeSocket(Object)接口用于关闭WebSocket连接。
■ wx.onSocketOpen(CallBack)接口 用于监听WebSocket连接打开事件。
■ wx.onSocketError(CallBack)接口 用于监听WebSocket错误。
■ wx.onSocketMessage(CallBack)接口 用于实现监听WebSocket接收到服务器的消息事件。
■ wx.onSocketClose(CallBack)接口 用于实现监听WebSocket关闭。
在本节,我们将介绍常用的3个网络API。
发起网络请求
wx. request(Object)实现向服务器发送请求、获取数据等各种网络交互操作,其相关参数如表6-1所示。一个微信小程序同时只能有5个网络请求连接,并且是HTTPS请求
例如,通过wx. request(Object)获取百度(https://www.baidu.com)首页的数据。(需要在微信公众平台小程序服务器配置中的request合法域名中添加“https://www.baidu.com”。)
示例代码如下:
index:wxml:
<button type="primary"bindtap ="getbaidutap">获取 HTML 数据</button>
<textarea value ='{{html}}'auto-heightmaxlength ='0'> </textarea>
index.js :
//.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方法获取邮政编码对应的地址信息。
示例代码如下:
index.wxml:
<view>邮政编码:</view >
<input type="text" bindinput="input" placeholder='6位邮政编码'/>
<button type="primary" bindtap="find">查询</button>
<block wx:for="{{address}}">
<block wx:for="{{item}}"><text>{{item}}</text></block>
</block >
index.js:
//postcode.js
Page({
data:{
postcode:"",
address:[],//邮政编码对应的地址
errMsg:"",
error_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;
//显示 toast 提示消息
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',//方法为GET
success:function(res){
wx.hideToast();//隐藏toast
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.reasonllres.data.reason,//错误原因分析
error_code:res.data.error_code
})
}
}
})
}
}
})
运行结果:
上传文件
wx. uploadFile(Object)接口用于将本地资源上传到开发者服务器,并在客户端发起一个HTTPS POST请求
通过wx. uploadFile(Object),可以将图片上传到服务器并显示。
index.wxml:
<button type="primary" bindtap="uploadimage">上传图片</button>
<image src="{{img}}"mode="widthFix"/>
index.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({
filePath: 'Path[0]',
name: 'file',
url: 'http://localhost/',
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();
}
})
}
}
})
运行结果:
下载文件
wx. downloadFile(Object)接口用于实现从开发者服务器下载文件资源到本地,在客户端直接发起一个HTTPGET请求,返回文件的本地临时路径。
例如,通过wx. downloadFile(Object)实现从服务器中下载图片,后台服务采用WAMP软件在本机搭建。
index.wxml:
<button type="primary" bind:tap="downloadimge">下载图像</button>
<image src="{{img}}"mode='widthFix'style = "width:90%;height:500px"></image>
index.js:
Page({
data:{
img:null,
},
downloadimage:function(){
var that = this;
wx.downloadFile({
url: "http://localhost/1.jpg", //通过WAMP软件实现
success:function(res){
console.log(res)
that.setData({
img:res.tempFilePath
})
}
})
}
})
运行结果:
多媒体API
多媒体API主要包括图片API、录音API、音频播放控制API、音乐播放控制API等,其目的是丰富小程序的页面功能。
图片API
图片API实现对相机拍照图片或本地相册图片进行处理,主要包括以下4个API接口:
■ wx.chooseImage(Object)接口用于从本地相册选择图片或使用相机拍照。
■ wx.previewImage(Object)接口 用于预览图片。
■ wx.getImageInfo(Object)接口用于获取图片信息。
■ wx.saveImageToPhotosAlbum(Object)接口 用于保存图片到系统相册。
1.选择图片或拍照
wx. chooseImage(Object)接口用于从本地相册选择图片或使用相机拍照。拍照时产生的临时路径在小程序本次启动期间可以正常使用,若要持久保存,则需要调用wx. saveFile保存图片到本地。
若调用成功,则返回tempFilePaths和tempFiles,tempFilePaths表示图片在本地临时文件路径列表。tempFiles表示图片的本地文件列表,包括path和size。
示例代码如下:
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(Object)接口主要用于预览图片
示例代码如下:
wx.previewImage({
current:"http://bmob - cdn - 16488.b0.upaiyun.com/2018/02/05/2.png",
urls:["https://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/2.png"
]
})
获取图片信息
wx. getImageInfo(Object)接口用于获取图片信息
示例代码如下:
wx.chooseImage({
success:function(res){
wx.getImageInfo({
src:res.tempFilePaths[0],
success:function(e){
console.log(e.width)
console.log(e.height)
}
})
},
})
保存图片到系统相册
wx. saveImageToPhotosAlbum(Object)接口用于保存图片到系统相册,需要得到用户授权scope.writePhotosAlbum。其相关参数如表6-7所示。
示例代码如下:
wx.chooseImage({
success:function(res){
wx.saveImageToPhotosAlbum({
filePath: 'res.TempFilePath[0]',
success:function(e){
console.log(e)
}
})
},
})
录音API
录音API提供了语音录制的功能,主要包括以下两个API接口:
■ wx.startRecord(Object)接口用于实现开始录音。
■ wx.stopRecord(Object)接口
用于实现主动调用停止录音。
1.开始录音
wx. startRecord(Object)接口用于实现开始录音。当主动调用wx.stopRecord(Object)接口或者录音超过1分钟时,系统自动结束录音,并返回录音文件的临时文件路径。若要持久保存,则需要调用wx. saveFile()接口。
停止录音
wx. stopRecord(Object)接口用于实现主动调用停止录音。
示例代码如下:
wx.startRecord)
({
success: function(res){
var tempFilePath= res.tempFilePath},
fail: function(res){
//录音失败
}
})
setTimeout(function(){//结束录音
wx.stopRecord()
},10000)
音频播放控制API
音频播放控制API主要用于对语音媒体文件的控制,包括播放、暂停、停止及audio组件的控制,主要包括以下3个API:
■ wx.playVoice(Object)接口 用于实现开始播放语音。
■ wx.pauseVoice(Object)接口用于实现暂停正在播放的语音。
■ wx.stopVoice(Object)接口 用于结束播放语音。
1.播放语音
wx. playVoice(Object)接口用于开始播放语音,同时只允许一个语音文件播放,如果前一个语音文件还未播放完,则中断前一个语音文件的播放。
示例代码如下:
wx.startRecord({
success: function(res){
var tempFilePath= res.tempFilePath wx.playVoice({//录音完后立即播放
filePath:tempFilePath, complete:function(){
}
})
}
})
暂停播放
wx. pauseVoice(Object)用于暂停正在播放的语音。再次调用wx.playVoice(Object)播放同一个文件时,会从暂停处开始播放。如果想从头开始播放,则需要先调用wx.stopVoice(Object)。
示例代码如下:
wx.startRecord({
success: function(res){
var tempFilePath = res.tempFilePath
wx.playVoice({ filePath:tempFilePath
})
setTimeout(function(){
//暂停播放
wx.pauseVoice()},5000)
}
})
结束播放
wx. stopVoice(Object)用于结束播放语音。
wx.startRecord({
success: function(res){
var tempFilePath =res.tempFilePath wx.playVoice({
filePath:tempFilePath})
setTimeout(function(){
wx.stopVoice()},5000)
}
})
音乐播放控制API
音乐播放控制API主要用于实现对背景音乐的控制,音乐文件只能是网络流媒体,不能是本地音乐文件。音乐播放控制API主要包括以下8个API:
■ wx.playBackgroundAudio(Object)接口 用于播放音乐。
■ wx.getBackgroundAudioPlayerState(Object)接口 用于获取音乐播放状态。
■ wx.seekBackgroundAudio(Object)接口 用于定位音乐播放进度。
■ wx.pauseBackgroundAudio()接口 用于实现暂停播放音乐。
■ wx.stopBackgroundAudio()接口 用于实现停止播放音乐。
■ wx.onBackgroundAudioPlay(CallBack)接口 用于实现监听音乐播放。
■ wx.onBackgroundAudioPause(CallBack)接口 用于实现监听音乐暂停。
■ wx.onBackgroundAudioStop(CallBack)接口 用于实现监听音乐停止。
1.播放音乐
wx. playBackgroundAudio(Object)用于播放音乐,同一时间只能有一首音乐处于播放状态,其相关参数如表6-10所示。
获取音乐播放状态
wx.getBackgroundAudioPlayerState(Object)接口用于获取音乐播放状态
接口成功后返回的参数
控制音乐播放速度
wx.seekBackgroundAudio(Object)接口用于控制音乐播放进度
暂停播放音乐
wx.pauesBackgroundAudio()接口用于暂停播放音乐
停止播放音乐
wx.stopBackgroundAudio()接口用于停止播放音乐
监听音乐播放
wx.onBackgroundAudioPlay(CallBack)接口用于实现监听音乐播放,通常被wx.playBackgroundAudio(Object)方法触发,在CallBack中可改变播放图标。
监听音乐暂停
wx. onBackgroundAudioPause (CallBack)接口用于实现监听音乐暂停,通常被 wx. pause-watepondhudio()方法触发。在 CallBeck 中可以改变播放图标。
监听音乐停止
wx. onBackgroundAudioStop(CallBack)接口用于实现监听音乐趾,通常被音乐自然播放停止或 wx. seekBackgroundAudio (Object)导致播放位置等于音乐总时长时触发。在CallBack 中可以改变图标。
案例展示
在此,以小程序 music 案例来展示音乐 API 的使用。该小目的4个页面文件分别为 music.wxml、 music. wxss、music.json和music.cojs。实际效果如图6-5所示。
index.wxml:
<view class="container">
<image class="bgaudio"src = "{{changedImg? music.coverImg:'/images/IMG10.jpg'}}"/>
<view class ="control-view">
<!--使用data-how定义一个0表示快退10秒-->
<image src ="/images/IMG9.jpg"bindtap="onPositionTap"data-how= "0 "/>
<image src = "/images/IMG11.jpg" bindtap = "onAudioTap"/>
<image src ="/images/IMG8.jpg"bindtap = "onStopTap"/><!--使用data-how定义一个1表示快进10秒-->
<image src ="/images/IMG7.jpg"bindtap ="onPositionTap"data-how = "1"/>
</view >
</view >
index.wxss:
.bgaudio{
height:350rpx; width:350rpx;
margin-bottom:100rpx;
}
.control-view image{
height:64rpx;
width:64rpx;
margin:30rpx;
}
index.js:
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。
1.保存文件
wx.saveFile(Object)用于保存文件到本地
示例代码如下:
saveImg:function(){
wx.chooseImage({
count:1,/默认值为9
sizeType:['original',compressed],/可以指定是原图还是压缩图,默认
者都有
sourceType:[album,camera’],/可以指定来源是相册还是相机,默认二
都有
success:function(res)var tempFilePaths =res.tempFilePaths0wx.saveFile(tempFilePath:tempFilePathssuccess:function(res)var saveFilePath =res.savedFilePath;
console.1og(saveFilePath)
}
})
}
})
}
示例代码如下:
2.获取本地文件列表
wx. getSavedFileList(Object)接口用于获取本地已保存的文件列表,如果调用成功,则返回文件的本地路径、文件大小和文件保存时的时间戳(从1970/01/01 08: 00: 00到当前时间的秒数)文件列表。
示例代码如下:
wx.getSavedFileList({
success:function(res){
that.setData({
fileList:res.fileList
})
}
})
3.获取本地文件的文件信息
wx. getSaveFileInfo(Object)接口用于获取本地文件的文件信息,此接口只能用于获取已保存到本地的文件,若需要获取临时文件信息,则使用wx. getFileInfo(Object)接口 。
示例代码如下:
wx.chooseImage({
count:1,/默认值为9sizeType:['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.1og(res.size)
}
})
}
})
}
})
4.删除本地文件
wx. removeSaveFile(Object)接口用于删除本地存储的文件
示例代码如下:
wx.getSavedFileList({
success:function(res){
if(res.fileList.length>0){
wx.removeSavedFile({
filePath:res.fileList[0],filePath,
complete:function(res){
console.log(res)
}
})
}
}
})
5.打开文档
wx.openDocument(Object)接口用于新页面打开文档,支持的格式有doc、xls、ppt、pdf、docx、xlsx、pptx,其相关参数如下
示例代码如下:
wx.downloadFile({
url: 'http://localhost/fm2.pdf',
success:function(res){
var tempFilePath = res.tempFilePath;
wx.openDocument({
filePath: 'tempFilePath',
success:function(res){
console.log("打开成功")
}
})
}
})