小程序开发,ajax封装
utils.js:
本人是promise函数的死忠粉…
const $ajax = function(url,data,method,loading = true){
let baseUrl_DEV = "xxx";
let headers_POST = {
"accessToken": "Bearer " + wx.getStorageSync('token'),
"Content-Type":"application/x-www-form-urlencoded"
}
let headers_GET = {
"accessToken": "Bearer " + wx.getStorageSync('token')
}
return new Promise((resolve,reject)=>{
if (loading) {
wx.showLoading({
title: '加载中...',
})
}
let that = this;
wx.request({
url: baseUrl_DEV+url,
method:method,
data : data,
header : method=="GET"? {...headers_GET}:{...headers_POST},
success(res){
resolve(res)
},
fail(err){
reject(err)
}
})
})
}
module.exports = {
formatTime: formatTime,
$ajax : $ajax
}
`
**注意:一定要在出口处暴露此方法,类似于es6 的exports default
**`
**新建一个js,取名叫common-api.js吧,用于存放可用的请求api
**
const util = require(’./util.js’);
let apis = {};
apis.getSubCatalogs = (id,params)=>{
return util.
a
j
a
x
(
‘
/
u
a
p
i
/
c
l
a
s
s
r
o
o
m
C
a
t
a
l
o
g
s
/
ajax(`/uapi/classroomCatalogs/
ajax(‘/uapi/classroomCatalogs/{id}/catalogs`,params,“GET”)
}
module.exports = {
…apis
}
最后,使用之
const ajax = require("…/…/utils/common-api.js");
ajax.getSubCatalogs(1,{id:3}).then(res=>{
console.log(res)
})