haixianTV 2016-11-23
微信小程序常用API
发起请求
wx.request发起的是 HTTPS 请求。一个微信小程序,同时只能有5个网络请求连接。
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})上传、下载
将本地资源上传到开发者服务器。如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。
wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success: function(res){
var data = res.data
//do something
}
})
}
})下载文件资源到本地。客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。
wx.downloadFile({
url: 'http://example.com/audio/123', //仅为示例,并非真实的资源
success: function(res) {
wx.playVoice({
filePath: res.tempFilePath
})
}
})注:文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,在小程序下次启动时才能访问得到。
本地缓存
wx.setStorage({
key:"key"
data:"value"
})
wx.getStorage({
key: 'key',
success: function(res) {
console.log(res.data)
}
})
wx.removeStorage({
key: 'key',
success: function(res) {
console.log(res.data)
}
})
wx.clearStorage()显示、隐藏消息提示框
wx.showToast({
title: '加载中',
icon: 'loading',
duration: 10000
})
setTimeout(function(){
wx.hideToast()
},2000)动态设置当前页面标题
wx.setNavigationBarTitle({
title: '当前页面'
}) 导航
wx.navigateTo({
url: 'test?id=1' // 保留当前页面,跳转到应用内的某个页面
})
wx.redirectTo({
url: 'test?id=1' // 关闭当前页面,跳转到应用内的某个页面
})