微信小程序常用js功能代码
时间: 2024-04-29 07:23:19 浏览: 9
1. 获取用户信息:
```
wx.getUserInfo({
success: function(res) {
var userInfo = res.userInfo;
var nickName = userInfo.nickName;
var avatarUrl = userInfo.avatarUrl;
var gender = userInfo.gender; //性别 0:未知、1:男、2:女
var province = userInfo.province;
var city = userInfo.city;
var country = userInfo.country;
}
})
```
2. 获取系统信息:
```
wx.getSystemInfo({
success: function(res) {
var systemInfo = res;
var screenWidth = systemInfo.screenWidth;
var screenHeight = systemInfo.screenHeight;
var language = systemInfo.language;
var version = systemInfo.version;
var platform = systemInfo.platform;
var model = systemInfo.model;
}
})
```
3. 发起网络请求:
```
wx.request({
url: 'https://example.com/api',
data: {
// 请求参数
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
console.log(res.data);
}
})
```
4. 设置本地存储:
```
wx.setStorage({
key: 'key',
data: 'value',
success: function(res) {
console.log('数据存储成功');
}
})
```
5. 获取本地存储:
```
wx.getStorage({
key: 'key',
success: function(res) {
console.log(res.data);
}
})
```
6. 弹出提示框:
```
wx.showModal({
title: '提示',
content: '这是一个模态弹窗',
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
})
```
7. 显示加载动画:
```
wx.showLoading({
title: '加载中',
})
```
8. 隐藏加载动画:
```
wx.hideLoading()
```
9. 滚动到页面顶部:
```
wx.pageScrollTo({
scrollTop: 0,
duration: 300
})
```
10. 获取当前页面的路径:
```
var pages = getCurrentPages();
var currentPage = pages[pages.length - 1];
var url = currentPage.route;
console.log(url);
```