6.1 网络API
微信小程序处理的数据通常从后台服务器获取,再将处理过的结果保存到后台服务器,这就要求微信小程序要有与后台进行交互的能力。微信原生API接口或第三方API提供了各类接口实现前后端交互。
网络API可以帮助开发者实现网络URL访问调用、文件的上传和下载、网络套接字的使用等功能处理。微信开发团队提供了10个网络API接口。
6.1.1 发起网络请求
wx.request实现向服务器发送请求、获取数据等各种网络交互操作,其相关参数如表6-1所示。一个微信小程序同时只能有5个网络请求连接,并且是HTTPS请求。
例如, 通过wx. request(Object)获取百度(https://www.baidu.com)首页的数据。示例代码如下:
baidu.wxml代码:
<button type="primary"bindtap ="getbaidutap">获取 HTML 数据</button>
<textarea value ='{{html}}'auto-heightmaxlength ='0'> </textarea>
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
})
}
})
}
})
运行结果:
6.1.2 上传文件
wx. uploadFile(Object)接口用于将本地资源上传到开发者服务器,并在客户端发起一个HTTPS POST请求,相关参数如下:
通过wx. uploadFile(Object),可以将图片上传到服务器并显示。示例代码如下:
upload.wxml代码:
<button type="primary"bindtap="uploadimage">上传图片</button >
<image src="../images/曹全碑.jpg"mode="widthFix"/>
upload.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.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(Object))
用于实现从开发者服务器下载文件资源到本地,在客户端直接发起一个HTTP GET 请求,返回文件的本地临时路径。
.wxml:
<button type="primary"bindtap='downloadimage'>下载图片</button>
<image src="{{img}}"mode='widthFix'style="width:90%;height:500px"/>
.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.chooseImage(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(Object)接口主要用于预览图片,相关参数如下:
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/2.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.getImage(object))
用于获取图片信息
wx.chooseImage({
success:function(res){
wx.getImageInfo({
src:res.tempFilePaths[0],
success:function(e){
console.log(width)
console.log(height)
}
})
}
})
保存图片到系统相册(wx.saveImageToPhotosAlbum(object))
用于保存图片到系统相册,需要得到用户授权scope.writePhotosAlbum。
wx.chooseImage({
success:function(res){
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePaths,
success:function(e){
console.log(e)
}
})
}
})
录音API
开始录音(wx.startRecord(object))
用于实现开始录音。主动调用接口或录音超过1分钟时,系统自动结束录音,并返回录音文件的临时文件路径。要持久保存。需要调用wx.saveFlie()
wx.startRecord({
success:function(res){
var tempFilePath =res.tempFilePath
},
fail:function(res){
}
})
停止录音(wx.stopRecord(object))
用于实现主动调用停止录音
wx.startRecord({
success:function(res){
var tempFilePath =res.tempFilePath
},
fail:function(res){
}
})
setTimeout(function(){
wx.stopRecord()
},10000)
音频播放控制API
播放录音(wx.playVoice(object))
用于开始播放语音,同时只允许一个语言文件播放。
wx.startRecord({
success:function(res){
var tempFilePath=res.tempFilePath
wx.playVoice({
filePath: 'tempFilePath',
complete:function(){
}
})
}
})
暂停录音(wx.pauseVoice(object))
用于暂停正在播放的语音。如果想从头播放需要调用wx.stopVoice()
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
播放音乐(wx.playBackgroundAudio(object))
用于播放音乐,同一时间只能有一首音乐处于播放状态
获取音乐播放状态(wx.getBackgroundAudioPlayerState(object))
用于获取音乐播放状态
控制音乐播放速度(wx.seekBackgroundAudio(object))
用于控制音乐播放速度
暂停播放音乐(wx.pauseBackgroundAudio())
用于暂停播放音乐
停止播放音乐(wx.stopBackgroundAudio())
用于停止播放音乐
监听音乐播放(wx.onBackgroundAudioPlay(CallBack))
用于实现监听音乐播放,通常被wx.playBackgroundAudio(Object)方法触发,在CallBack中可改变播放图标
监听音乐暂停(wx.onBackgroundAudioPause(CallBack))
用于实现监听音乐暂停,通常被wx.pauseBackgroundAudio(Object)方法触发,在CallBack中可改变播放图标
监听音乐停止(wx.onBackgroundAudioStop(CallBack))
用于实现监听音乐停止,通常被音乐自然播放停止或wx.seekpBackgroundAudio(Object)方法导致播放位置等于音乐总时长时触发,在CallBack中可改变播放图标
示例代码:
.js:
.js
Page({
data:{
isPlaying:false,
changedImg:false,
music:{
"url":"http://bomb-cdn-16488.b0.upaiyun.com/2018/02/09/117e4a1b405195b18061299e2de89597.mp3",
"title":"盛晓玫 -有一天",
"coverImg":
"http://bmob-cdn-16488.b0upaiyun.com/2018/02/09/f604297140c9681880cc3d3e581f7724"
},
},
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.dataset.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: '快进10s',
duration:500
});
}
}else{
wx.showToast({
title: '音乐未播放',
duration:800
});
}
}
})
},
onAudioState:function(){
let that=this;
wx.onBackgroundAudioPlay(function(){
that.setData({isPlaying:true,changedImg:true});
console.log("on play");
});
wx.onBackgroundAudioPause(function(){
that.setData({isPlaying:flase});
console.log("on pause");
});
wx.onBackgroundAudioStop(function(){
that.setData({isPlaying:flase,changedImg:flase});
console.log("on stop");
})
}
})
.wxml:
<view class="container">
<image class="bgaudio"src="{{changedImg?music.coverImg:'/images/1.jpg'}}"/>
<view class="control-view">
<!-- 使用data-how定义一个0表示快退10秒 -->
<image src="/images/2.jpg"bindtap="onPositionTap"data-how="0"/>
<image src="/images/3.jpg"bindtap="onAudioTap"/>
<image src="/images/hh.jpg"bindtap="onStopTap"/>
<!-- 使用data-how定义一个1表示快进10秒 -->
<image src="/images/jc.jpg"bindtap="onPositionTap"data-how="1"/>
</view>
</view>
.wxss:
.bgaudio{
height:350rpx;
width:250rpx;
margin-bottom: 100rpx;
}
.control-viewimage{
height: 64rpx;
width:64rpx;
margin: 30rpx;
}
文件API
保存文件(wx.saveFile(object))
用于保存文件到本地
.js
Page({
saveImg:function(){
wx.chooseImage({
count:1,
sizeType:["original",'compressed'],
sourceType:['album','camera'],
success:function(res){
var tempFilePaths=res.tempFilePaths[0]
wx.saveFile({
tempFilePaths:tempFilePaths,
success:function(res){
var saveFilePath=res.savedFilePath;
console.log(saveFilePath)
}
})
}
})
}
})
获取本地文件列表(wx.getSavedFileList(object))
用于获取本地已保存的文件列表,如果调用成功,则返回文件的本地路径、文件大小和文件保存时的时间戳点。
/*.js*/
wx.getSavedFileList({
success:function(res){
that.setData({
fileList:res.fileList
})
}
})
获取本地文件的文件信息(wx.getSaveFileInfo(object))
用于获取本地文件的文件信息,此接口只能用于获取已保存到本地的文件
wx.chooseImage({
count:1,
sizeType:["original",'compressed'],
sourceType:['album','camera'],
success:function(res){
var tempFilePaths=res.tempFilePaths[0]
wx.saveFile({
tempFilePaths:tempFilePaths,
success:function(res){
var saveFilePath=res.saveFilePath;
wx.getSavedFileInfo({
filePath:saveFilePath,
success:function (res){
console.log(res.size)
}
})
}
})
}
})
删除本地文件(wx.removeSaveFile(object))
用于删除本地的储存的文件
wx.getSavedFileList({
success:function (res) {
if(res.fileList.lenght>0){
wx.removeSavedFile({
filePath:res.fileList[0],filePath,
complete:function (res) {
console.log(res)
}
})
}
}
})
打开文档(wx.openDocument(object))
用于新开页面打开文档
wx,wx.downloadFile({
url: 'http://localhost/fm2.pdf',
success:function (res) {
var tempFilePath=res.tempFilePath;
wx.openDocument({
filePath:tempFilePath,
success:function (res) {
console.log("打开成功")
}
})
}
})
异步和同步的区别:
同步和异步是计算机编程中处理数据传输和任务执行的两种不同方法,两者之间的主要区别在于数据传输或任务执行的方式。
同步:指的是在程序执行过程中,等待一个操作(如数据请求)完成后再继续执行下一行代码,如果数据尚未准备好,客户端(或服务端)会一直等待,直到数据准备好并返回这种方式的优点是简单明了,适用于数据处理简单、数据量小的场景。
异步:指的是在程序执行过程中,不等待某个操作完成而是继续执行下一行代码,同时,操作会在后台进行,当作完成后,会通过某种方式(如回调函数、事件等)通知程序,这种方式适用于数据处理复杂、数据量大的场景,因为它允许程序在等待操作完成的同时执行其他任务,提高了程序的效率和响应速度。
本地数据及缓存API
是永久存储的,但最大不超过10MB,目的提高加载速度。
带由Sync后缀的为同步接口,不带Sync后缀的为异步接口。
保存数据
wx.getStorage(Object)
将数据存储到本地缓存接口指定的key中,接口执行后会覆盖原来key对应的内容。
.js
wx.setStorage({
key:'name',
data:'sdy',
success:function(res){
console.log(res)
}
})
wx.setStorageSync(key,data)
是同步接口,参数只有key和data
.js
wx.setStorageSync('age','25')
获取数据
wx.getStorage(Object)
是从本地缓存中异步获取指定key对应的内容。
wx.getStorage({
key:'name',
success:function(res){
console.log(res)
},
})
wx.setStorageSync(key)
从本地缓存中同步获取指定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对应的内容,参数只有key
try{
wx.removeStorageSync('name')
}catch(e){
}
清空数据
wx.clearStorage(Object)
用于异步清理本地数据缓存。没有参数。
wx.getStorage({
key:'name',
success:function(res){
wx.clearStorage()
}
})
wx.clearStorageSync()
用于同步清理本地数据缓存
try{
wx.clearStorageSync()
}catch(e){
}
位置信息API
获取位置信息(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({
success:function (res) {
console.log("位置的名称:"+res.name)
console.log("位置的地址:"+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 longtitude=res.longitude
wx.openLocation({
latitude:latitude,
longitude:longtitude,
scale:10,
name:'智慧国际酒店',
address:'西安市长安区西长安区300号'
})
}
})
设备相关API
获取系统信息(wx.getSystemInfo(Object)、wx.getSystemInfoSync(Object))
分别用于异步和同步获取系统信息。
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)
}
})
网络状态
1.获取网络状态(wx.getNetworkType(Object))
成功调用后,返回网络类型包:wifi/2G/3G/4G/unknown(Android下不常见的网络类型)/none(无网络)
wx.getNetworkType({
success:function (res) {
console.log(res.networkType)
}
})
2.监听网络状态变化(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:function (res) {
console.log(res.result)
console.log(res.scanType)
console.log(res.charSet)
console.log(res.path)
}
})
//只允许从相机扫码
wx.scanCode({
onlyFromCamera:true,
success:function (res) {
console.log(res)
}
})