一`网络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。
1.发起网络请求
wx.request(Object)相关参数:
<button type="primary" bindtap="getbaidutap">获取HTML数据</button>
<textarea value ='{{html}}'auto-heightmaxlength='0'> </textarea>
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方式获取邮政编码对应的地址信息
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;
wx.showToast({
title: '正在查询,请稍后...',
icon:'loading',
duration:10000
});
wx:wx.request({
url: 'https://v.juhe.cn/postcode/query',
data:{
'postcode':postcode,
'key':'0ff9bfccdf147476e067de994eb5496e'
},
header:{
'Comtent-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
})
}
}
})
}
}
})
<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>
运行结果:
2.上传文件
<button type="primary" bindtap="uploadimage">上传图片</button>
<image src="{{img}}"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({
filePath: 'path[0]',
name: 'file',
url: "http://localhost",
success:function(res){
console.l0g(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();
}
})
}
}
})
运行结果:
->点击上传图片后选择图片
3.下载文件
二.多媒体API
1.图片API
1).选择图片或拍照
//js代码:
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)
}
})
运行结果会打开你的图片文件夹
eg:
2).预览图片
//js
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"
]
})
3).获取图片信息
wx.chooseImage({
success:function(res){
wx.getImageInfo({
src:res.tempFilePaths[0],
success:function(e){
console.log(e.width)
console.log(e.width)
}
})
},
})
4).保存图片到系统相册
wx.chooseImage({
success:function(res){
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePaths[0],
success:function(e){
console.log(e)
}
})
},
})
2.录音API
1).开始录音
2).停止录音
wx.startRecord({
success:function(res){
var tempFilePath=res.tempFilePath
},
fail:function(res){
}
})
setTimeout(function(){
wx.stopRecord()
},10000)
3.音频播放控制API
1).播放语音
wx.playVoice(Object)接口 实现开始播放语音
wx.startRecord({
success:function(res){
var tempFileOath=res.tempFilePath
wx.playVoice({
filePath:tempFilePath,
complete:function(){
}
})
}
})
2).暂停播放
wx.pauseVoice(Object)接口 用于实现暂停正在播放的语音
wx.startRecord({
success:function(res){
var tempFileOath=res.tempFilePath
wx.playVoice({
filePath:tempFilePath
})
setTimeout(function(){
wx.pauseVoice()
},5000)
}
})
3).结束播放
wx.stopVoice(Object)接口 实现结束语音
wx.startRecord({
success:function(res){
var tempFileOath=res.tempFilePath
wx.playVoice({
filePath:tempFilePath
})
setTimeout(function(){
wx.stopVoice()
},5000)
}
})
4.音乐播110放控制API
1).播放音乐
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)
}
})
2).获取音乐播放状态
接口调用成功后返回的参数:
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("音乐文件的下载进度:"+status)
}
})
3).控制音乐播放进度
wx.seekBackgroundAudio({
position:30
})
4).暂停播放音乐
wx.playBackgroundAudio({
dataUrl:'/music/a.mp3',
title:'我的音乐',
coverImgUrl:'/image/zy1.jpg',
success:function(){
console.log('开始播放音乐');
}
});
setTimeout:(function(){
console.log('暂停播放');
wx.pauseBackgroundAudio();
},5000);
5).停止播放音乐
wx.playBackgroundAudio({
dataUrl:'/music/a.mp3',
title:'我的音乐',
coverImgUrl:'/image/zy1.jpg',
success:function(){
console.log('开始播放音乐');
}
});
setTimeout:(function(){
console.log('暂停播放');
wx.stopBackgroundAudio();
},5000);
6).监听音乐播放
7).监听音乐暂停
wx.onBackgroundAudioPause(CallBack)接口用于实现监听音乐暂停,通常被 wx. pause Background Audio()方法触发。在CallBack中可以改变播放图标。
8).监听音乐停止
wx.onBackgroundAudioStop(CallBack)接口用于实现监听音乐停止,通常被音乐自然播放停止或wx. seekBackgroundAudio(Object)方法导致播放位置等于音乐总时长时触发。在CallBack中可以改变播放图标。
9).案例展示
在此,以小程序 music为案例来展示音乐API的使用。该小程序的4个页面文件分别为music.wxml、music. wxss、music. json和 music.cojs。
实际效果如图所示:
music. wxml的代码如下:
三.文件API
1.保存文件
wx.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','camera'],
success:function(res){
var tempFilePaths=res.tempFilePaths[0]
wx.saveFile({
tempFilePath:tempFilePath,
success:function(res){
var saveFilePath=res.saveFilePath;
console.log(saveFilePath)
}
})
}
})
2.获取本地文件列表
wx.getSaveFileList({
success:function(res){
that.setData({
fileList:res.fileList
})
}
})
3.获取本地文件的文件信息
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)
}
})
}
})
}
})
4.删除本地文件
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.downloadFile({
url: "http://localhost/fm2.pdf",
success:function(res){
var tempFilePath=res.tempFilePath;
wx.openDocument({
success:function(res){
console.log("打开成功")
}
})
}
})
四.本地数据及缓存API
1.保存数据
wx.setStorage({
key:'name',
data:'sdy',
success:function(res){
console.log(res)
}
})
2.获取数据
异步:
wx.getStorage({
key:'name',
success:function(res){
console.log(res.data)
},
})
同步:
try{
var value =wx.getStorageSync('age')
if(value){
console.log("获取成功"+value)
}
}catch(e){
console.log("获取失败")
}
3.删除数据
异步:
wx.removeStorage({
key: 'name',
success:function(res){
console.log("删除成功")
},
fail:function(){
console.log("删除失败")
}
})
同步:
try{
wx.removeStorageSync('name')
} catch (e){
//Do something when catch error
}
4.清空数据
wx.clearStorage()接口用于异步清理本地数据缓存,没有参数.
wx.getStorage({
key:'name',
success:function(res){
wx.clearStorage()
},
})
wx.clearStroageSync()接口用于同步清理本都缓存数据.
try{
wx.clearStorageSync()
}catch(e){
}
五.位置信息API
1.获取位置信息
wx.getLocation({
type:'wgs84',
success:function(res){
console.log("经度:"+res.longitude);
console.log("纬度:"+res.lattude);
console.log("速度:"+res.longitude);
console.log("位置的精准度:"+res.accuracy);
console.log("水平精准度:"+res.horizontalAccuracy);
console.log("垂直精准度:"+res.varticalAccracy);
},
})
2.选择位置信息
wx.chooseLocation({
success:function(res){
console.log("位置的名称:"+res,name)
console.log("位置的地址:"+res,address)
console.log("位置的经度:"+res,longitude)
console.log("位置的纬度:"+res,latitude)
}
})
3.显示位置信息
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.getSystemInfoSync()接口用于获取系统信息
wx. getNetworkType(Object)接口 用于获取网络类型。
wx.onNetworkStatusChange(CallBack)接口 用于监测网络状态改变。
wx. makePhoneCall(Object)接口 用于拨打电话。
wx.scanCode(Object)接口用于扫描二维码。
1.获取系统信息
wx.getSystemInfo(Object)接口、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)
},
})
2.网络状态'
wx.getNetworkType({
success:function(res){
console.log(res.networkType)
},
})
监听网络状态变化
wx.onNetworkStatusChange(function(res){
console.log("网络是否连接:"+res.isConnected)
console.log("变化后的网络类型:"+res.networkType)
})
3.拨打电话
wx.makePhoneCall相关参数:
wx.makePhoneCall({
phoneNumber:'13277839686'
})
4.扫描二维码
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等。通过对本章的学习,大家应深刻地理解各类API是开发各类小程序的核心。