.1网络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 关闭。
在本节,我们将介绍常用的3个网络API
6.1.1 发起网络请求
wx.request(0bject)实现向服务器发送请求、获取数据等各种网络交互操作,其相关参数如表所示。一个微信小程序同时只能有5个网络请求连接,并且是HTTPS请求
例如,通过 wx.requesl(0bject)获取百度(https:// www,baidu.com)首页的数据。(需要在微信公众平台小程序服务器配置中的request合法域名中添加“htps:// www.baidu.com”。)
<!-- 发起网络请求 wxml文件 -->
<button type="primary" bind:tap="getbaidutap">获取HTML数据</button>
<textarea value="{{html}}" auto-height="" maxlength="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
})
}
})
}
})
/* 发起网络请求 wxss文件*/
button{
margin-top: 100px;
}
通过wx.request(Object)的GET方法获取邮政编码对应的地址信息。示例代码如下:
<!-- postcode wxml文件 -->
<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder="6位邮政编码"/>
<button type="primary" bind:tap="find">查询</button>
<block wx:for="{{address}}">
<block wx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>
Page({
// postcode js文件
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',
},
//方法为GET
method:'GET',
success:function(res){
//隐藏toast
wx.hideToast();
if(res,this.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(0bject)的POST方法获取邮政编码对应的地址信息示例代码如下:
<!-- postcode wxml文件 -->
<view>邮政编码:</view>
<input type="text" bindinput="input" placeholder="6位邮政编码"/>
<button type="primary" bind:tap="find">查询</button>
<block wx:for="{{address}}">
<block wx:for="{{item}}">
<text>{{item}}</text>
</block>
</block>
Page({
// postcode js文件
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/X-www-form-urlencoded',
},
//方法为GET
method:'POST',
success:function(res){
//隐藏toast
wx.hideToast();
if(res,this.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
})
}
}
})
}
}
})
6.1.2 上传文件
wx.uploadFile(Object)接口用于将本地资源上传到开发者服务器,并在客户端发起一个HTTPS POST请求,其相关参数如表所示
通过 wx.uploadFile(Objeet),可以将图片上传到服务器并显示,示例代码如下:
<!-- 上传文件 wxml文件 -->
<button type="primary" bind:tap="uploadimage">上传图片</button>
<image src="{{img}}" mode="widthFix"></image>
// 上传文件 js文件
Page({
data:{
img:null,
},
uploadumage:function(){
var that=this;
//选择图片
wx.chooseImage({
success:function(res){
var tempFilePaths=res.tempFilePaths
upload(that.tempFilePaths);
}
})
//显示toast提示消息
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
})
},
//隐藏Toast
complete:function(){
wx.hideToast();
}
})
}
}
})
/* 上传文件 wxss文件*/
button{
margin-top: 100px;
}
6.1.3 下载文件
wx.downloadFile(Objeet)接口用于实现从开发者服务器下载文件资源到本地,在客户端
直接发起一个HITPGET请求,返回文件的本地临时路径。其相关参数如表所示
例如,通过wx.downloadFile(Object)实现从服务器中下载图片,后台服务采用WAMP软件在本机搭建,示例代码如下:
<!-- 下载图像 wxml文件 -->
<button type="primary" bind:tap="downloadimage">下载图像</button>
<image src="{{img}}" mode="widthFix" style="width: 90%;height: 500px;"></image>
// 下载图像 js文件
Page({
datd:{
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
})
}
})
}
})
/* 下载图像 wxss文件 */
button{
margin-top: 100px;
}
6.2 多媒体 API
多媒体API主要包括图片API、录音API、音频播放控制AP1、音乐播放控制API等,其目的是丰富小程序的页面功能
6.2.1 图片API
(1)wx.chooselmage(Object)接口 用于从本地相册选择图片或使用相机拍照
(2)wx.previewlmage(Object)接口用于预览图片
(3)wx.getlmagelnfo(0bject)接口 用于获取图片信息。
(4)wx.saveImageToPhotosAlbum(0bject)接口 用于保存图片到系统相册。
以下代码都属于JS文件内的
1.选择图片或拍照
wx.chooselmage(Object)接口用于从本地相册选择图片或使用相机拍照。拍照时产生的临时路径在小程序本次启动期间可以正常使用,若要持久保存,则需要调用wsaveFile保存图片到本地。其相关参数如表所示
若调用成功,则返回tempFilePaths和tempFiles,tempFilePaths表示图片在本地临时文件路径列表。tempFiles表示图片的本地文件列表,包括path和size,示例代码如下:
Js文件
Page({
wx.chooseImage({
//默认值为9
count:2,
//可以指定是原图还是压缩图,默认二者都有
sizeType:['original','compressed'],
//可以指定来源是相册还是相机,默认二者都有
sourceType:['album','camera'],
success:function(res){
//返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的sec属性来显示图片
var tempFilePaths=res.tempFilePaths
var tempFiles=res.tempFiles
console.log(tempFilePaths)
console.log(tempFiles)
}
})
})
2.预览图片
wx.previewlmage(0bject)接口主要用于预览图片,其相关参数如表所示
page({
wx.previewImage({
current:"http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
urls: ["http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/1.png",
"http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/2.png",
"http://bomob-cdn-16488.b0.upaiyun.com/2018/02/05/3.png"
],
})
})
6.2.2 录音API
录音API提供了语音录制的功能,主要包括以下两个API接口:
(1)wx.stariRecord(Object)接口 用于实现开始录音。
(2)wx.stopRecord(Objeet)接日 用于实现主动调用停止录音
1.开始录音
wx. startRecord(0bject)接口用于实现开始录音。当主动调用wx.stopRecord(Object)接口或者录音超过1分钟时,系统自动结束录音,并返回录音文件的临时文件路径。若要持久保存,则需要调用 wx.saveFile()接口。其相关参数如表所示
2.停止录音
ws.slopReeord(Objeet)接口用于实现主动调用停止录音,示例代码如下:
wx.startRecord({
success:function(res){
var tempFilePath=res.tempFilePath
},
fail:function(res){
//录音失败
}
}),
setTimeout(function() {
//结束录音
wx.stopRecord()
},10000)
6.2.3 音频播放控制API
音频播放控制API主要用于对语音媒体文件的控制,包括播放、暂停、停止及audio组件的控制,主要包括以下3个API;
(1)wx,playVoice(Object)接口 用于实现开始播放语音
(2)wx.pauseVoice(Object)接日 用于实现暂停正在播放的语音
(3)wx, slopVoice(Objec)接日 用于结束播放语音
1.播放语音
wx.playVoice(Object)接口用于开始播放语音,同时只允许一个语音文件播放,如果前一个语音文件还未播放完,则中断前一个语音文件的播放。其相关参数如表所示
wx.startRecord({
success:function(res) {
var tempFilePath=res.tempFilePath
wx.playVoice({
filePath: tempFilePath,
complete:function() {
}
})
}
})
6.2.4 音乐播放控制API
音乐播放控制API主要用于实现对背景音乐的控制,音乐文件只能是网络流媒体,不能是本地音乐文件。音乐播放控制API主要包括以下8个API:
(1)wx.playBackgroundAudio(Object)接 用于播放音乐。
(2)wx. getBackgroundAudioPlayerState(Object)接口 用于获取音乐播放状态,
(3)wx.seekBackgroundAudio(0bject)接口 用于定位音乐播放进度。
(4)wx.pauseBackgroundAudio()接口 用于实现暂停播放音乐。
(5)wx.stopBackgroundAudio()接口 用于实现停止播放音乐。
(6)wx.onBackgroundAudioPlay(CallBack)接日 用于实现监听音乐播放
(7)wx.onBaekgroundAudioPause(CalBack)接口 用于实现监听音乐暂停
(8)wx.onBackgroundAudioStop(CallBack)接口 用于实现监听音乐停止。
4.暂停播放音乐
wx.pauseBackgroundAudio()接口用于暂停播放音乐
5.停止播放音乐
wx.stopBackgroundAudio()接口用于停止播放音乐
6.监听音乐播放
wx. onBackgroundAudioPlay(CallBack)接口用于实现监听音乐播放,通常被 wx. playBackgroundAudio(Object)方法触发,在CallBack中可改变播放图标
7.监听音乐暂停
wx.onBackgroundAudioPause(CallBack)接口用于实现监听音乐暂停,通常被wx.pauseBackgroundAudio()方法触发。在CallBack中可以改变播放图标
8.监听音乐停止
wx.onBackgroundAudioStop(CallBack)接口用于实现监听音乐停止,通常被音乐自然播放停止或wx.seekBackgroundAudio(Object)方法导致播放位置等于音乐总时长时触发。在CallBack中可以改变播放图标
9.案例展示