模式切换
API 调用
网络请求:wx.request
这是小程序中最常用的 API,用于向服务器发送 HTTP/HTTPS 请求,获取或提交数据。
核心要点:
- 域名限制:请求的域名必须在小程序后台的「开发」-「开发管理」-「开发设置」-「服务器域名」中配置,否则在真机上无法请求(开发工具中可临时开启不校验域名)。
- 默认超时:默认超时时间为 60 秒。
- HTTPS:网络请求必须使用 HTTPS 协议。
常用参数:
url
:开发者服务器接口地址 (必需)method
:HTTP 请求方法 (GET, POST 等),默认为 GETdata
:请求的参数header
:设置请求的 headersuccess
:接口调用成功的回调函数fail
:接口调用失败的回调函数complete
:接口调用结束的回调函数(调用成功、失败都会执行)
javascript
// 示例:获取文章列表
Page({
data: {
articles: []
},
onLoad: function() {
this.getArticles();
},
getArticles: function() {
wx.request({
url: 'https://your-api-domain.com/api/articles',
method: 'GET',
data: {
page: 1,
limit: 10
},
header: {
'content-type': 'application/json' // 默认值,如果传输JSON数据可以这样写
// 如果需要携带 token,可以在这里添加:
// 'Authorization': 'Bearer ' + token
},
success: (res) => {
// res.data 是服务器返回的数据
if (res.statusCode === 200) {
this.setData({
articles: res.data.data
});
} else {
wx.showToast({
title: '数据加载失败',
icon: 'none'
});
}
},
fail: (err) => {
console.error('请求失败', err);
wx.showToast({
title: '网络错误',
icon: 'none'
});
}
});
}
})
数据缓存:本地存储
小程序的本地存储类似于 Web 的 LocalStorage,但容量更大(最大 10MB),并且提供了同步和异步两套 API。
常用 API:
异步版本:
wx.setStorage
:异步存储数据wx.getStorage
:异步读取数据wx.removeStorage
:异步删除数据wx.clearStorage
:异步清空所有数据
同步版本 (推荐,更简洁):
wx.setStorageSync
:同步存储数据wx.getStorageSync
:同步读取数据wx.removeStorageSync
:同步删除指定 key 的数据wx.clearStorageSync
:同步清空所有数据
javascript
// 同步缓存示例:存储用户 token 和获取用户信息
Page({
// 存储数据
saveUserInfo: function(userInfo) {
try {
wx.setStorageSync('userInfo', userInfo);
wx.setStorageSync('token', 'abc123xyz');
console.log('存储成功');
} catch (e) {
console.error('存储失败', e);
}
},
// 读取数据
onLoad: function() {
try {
const userInfo = wx.getStorageSync('userInfo');
const token = wx.getStorageSync('token');
if (userInfo && token) {
this.setData({ userInfo });
// 使用 token 进行后续操作...
}
} catch (e) {
console.error('读取失败', e);
}
},
// 清除数据
clearStorage: function() {
try {
// 清除指定的数据
wx.removeStorageSync('token');
// 或者清除所有数据
// wx.clearStorageSync();
} catch (e) {
console.error('清除失败', e);
}
}
})
媒体操作
wx.chooseImage - 选择图片
从本地相册选择图片或使用相机拍照。
javascript
wx.chooseImage({
count: 1, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths;
this.setData({
avatar: tempFilePaths[0]
});
}
})
wx.previewImage - 预览图片
在新页面中全屏预览图片,可以滑动查看多张图片。
javascript
// 预览单张图片
wx.previewImage({
current: 'https://example.com/image1.jpg', // 当前显示图片的http链接
urls: ['https://example.com/image1.jpg'] // 需要预览的图片http链接列表
});
// 预览多张图片(如九宫格)
previewImages: function(e) {
const currentUrl = e.currentTarget.dataset.url;
const allUrls = this.data.imageList.map(item => item.url);
wx.previewImage({
current: currentUrl,
urls: allUrls
});
}
设备信息:wx.getSystemInfo
获取手机系统信息,常用于做屏幕适配或判断设备类型。
javascript
// 异步获取
wx.getSystemInfo({
success: (res) => {
console.log(res.model); // 手机型号
console.log(res.platform); // 客户端平台
console.log(res.system); // 操作系统版本
console.log(res.screenWidth, res.screenHeight); // 屏幕宽高
console.log(res.windowWidth, res.windowHeight); // 可使用窗口宽高
console.log(res.statusBarHeight); // 状态栏的高度(非常常用!)
this.setData({
statusBarHeight: res.statusBarHeight,
isIphoneX: res.model.includes('iPhone X')
});
}
})
// 同步获取(更常用)
try {
const systemInfo = wx.getSystemInfoSync();
console.log(systemInfo.windowWidth);
} catch (e) {
console.error('获取系统信息失败', e);
}
位置信息:wx.getLocation
获取当前的地理位置、速度。
注意:此 API 需要用户授权,且需要在 app.json
中配置权限。
json
// app.json
{
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
}
}
javascript
wx.getLocation({
type: 'wgs84', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: (res) => {
const latitude = res.latitude; // 纬度
const longitude = res.longitude; // 经度
const speed = res.speed; // 速度
const accuracy = res.accuracy; // 位置的精确度
console.log(`当前位置:纬度 ${latitude}, 经度 ${longitude}`);
// 可以配合 wx.openLocation 查看位置
wx.openLocation({
latitude,
longitude,
scale: 18
});
},
fail: (err) => {
console.error('获取位置失败', err);
wx.showModal({
title: '提示',
content: '需要您授权位置信息才能使用此功能',
success: (res) => {
if (res.confirm) {
// 用户点击确定,可以引导用户去设置页开启权限
wx.openSetting();
}
}
});
}
})
界面交互
wx.showToast - 消息提示框
显示轻量级的提示,自动消失。
javascript
// 成功提示
wx.showToast({
title: '操作成功',
icon: 'success',
duration: 2000
});
// 加载中
wx.showToast({
title: '加载中...',
icon: 'loading',
duration: 2000
});
// 纯文本提示(无图标)
wx.showToast({
title: '这是纯文本提示',
icon: 'none', // 重要!没有图标
duration: 2000
});
// 自定义时长
wx.showToast({
title: '我会显示5秒',
icon: 'none',
duration: 5000
});
wx.showModal - 模态对话框
显示有确认和取消按钮的对话框,用于重要操作确认。
javascript
wx.showModal({
title: '提示',
content: '您确定要删除这项内容吗?',
confirmColor: '#ff4757', // 确认按钮的文字颜色
cancelColor: '#57606f', // 取消按钮的文字颜色
success: (res) => {
if (res.confirm) {
console.log('用户点击确定');
// 执行删除操作
} else if (res.cancel) {
console.log('用户点击取消');
}
}
})
wx.showLoading 和 wx.hideLoading - 加载提示
显示加载提示,需要手动调用 wx.hideLoading
关闭。
javascript
// 显示加载提示
wx.showLoading({
title: '加载中...',
mask: true // 是否显示透明蒙层,防止触摸穿透
});
// 模拟网络请求
setTimeout(() => {
// 请求完成,隐藏加载提示
wx.hideLoading();
}, 2000);
// 或者在 wx.request 的 success/fail/complete 中调用 wx.hideLoading()
wx.request({
url: 'https://api.example.com/data',
beforeSend: () => {
wx.showLoading({ title: '加载中...', mask: true });
},
complete: () => {
wx.hideLoading();
}
});