微信小程序请求处理,ajax请求
·
一、wx.request() 发起请求
发起 HTTPS 网络请求。详细参考:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
wx.request({
url: 'example.php', //仅为示例,并非真实的接口地址
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
data 参数说明
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
- 对于
GET方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...) - 对于
POST方法且header['content-type']为application/json的数据,会对数据进行 JSON 序列化 - 对于
POST方法且header['content-type']为application/x-www-form-urlencoded的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
二、使用封装,requestHelper.js
1.封装 requestHelper.js
var req = {
//get请求处理
get: function (url, data, onSuccess) {
var app = getApp();
if (data && app && app.globalData && app.globalData.userInfo != null) {
data["userid"] = app.globalData.userInfo.id;
}
//处理null
var param = {};
for (var p in data) {
if (data.hasOwnProperty(p)) {
if (data[p] != null)
param[p] = data[p];
}
}
wx.request({
url: url,
data: param,
method: 'GET',
header: {
'content-type': 'application/x-www-form-urlencoded' // 表单提交处理
},
success: function (res) {
if (res.statusCode == 509) {
wx.showModal({
title: '错误',
content: res.data,
showCancel: false,
success: res => {
//清空登录用户
//wx.clearStorageSync();
wx.removeStorageSync('user4');
wx.navigateTo({
url: '/pages/login/login',
})
}
})
} else {
if (onSuccess)
onSuccess(res.data);
}
}
});
},
//Post
post: function (url, data, onSuccess) {
//post提交处理
var app = getApp();
if (data && app.globalData && app.globalData.userInfo != null) {
data["userid"] = app.globalData.userInfo.id;
}
//处理null
var param = {};
for (var p in data) {
if (data.hasOwnProperty(p)) {
if (data[p] != null)
param[p] = data[p];
}
}
wx.request({
url: url,
data: param,
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' // 表单提交处理
},
success: function (res) {
if (res.statusCode == 509) {
wx.showModal({
title: '错误',
content: res.data,
showCancel: false,
success: res => {
//清空本地缓存
wx.clearStorageSync();
wx.navigateTo({
url: '/pages/login/login',
})
}
})
} else {
if (onSuccess)
onSuccess(res.data);
}
}
});
}
}
module.exports = req;
2.使用requestHelper.js
/**
* 文章查询操作
*/
var url = require('../utils/urlHelper.js');
var req = require('../utils/requestHelper.js');
var article = {
// 获取系统公告列表
getNotice: function (skip, onSuccess) {
var link = url.getArticle('getlist');
req.get(link, { skip: skip }, function (data) {
if(onSuccess) onSuccess(data)
});
},
// 获取系统公告详情
getDetail: function (id, onSuccess) {
var link = url.getArticle('getmodel');
req.get(link, { id: id }, function (data) {
if (onSuccess) onSuccess(data)
});
}
}
module.exports = article;
更多:
微信小程序类库封装模块化、基础类库
微信小程序生命周期_页面生命周期
微信小程序坐标位置使用整理(四)map组件
更多推荐


所有评论(0)