var API_URL = \'https://web.ynstkz.com/\';
var token;
var requestHandler = {
url:{},
params: {},
header:{},
success: function (res) {
// success
},
fail: function () {
// fail
},
}
//GET请求
function GET(requestHandler) {
wx.getStorage({
// wx.getStorageSync({
key: \'token\',
success(res) {
token = res.data.token
}, fail(res) {
console.log(\'1\')
token = \'\'
}, complete(res) {
request(\'GET\', requestHandler)
}
})
}
//POST请求
function POST(requestHandler) {
wx.getStorage({
// wx.getStorageSync({
key: \'token\',
success(res) {
token = res.data.token
},fail(res) {
console.log(\'1\')
token = \'\'
}, complete(res) {
request(\'POST\', requestHandler)
}
})
}
function request(method, requestHandler) {
var that=this;
//注意:可以对params加密等处理
var params = requestHandler.params;
var headers;
headers={
\'content-type\': method == \'POST\' ?
\'application/x-www-form-urlencoded\' : \'application/json\',
\'stkjtoken\': token
}
console.log(token)
wx.request({
url: API_URL + requestHandler.url,
data: params,
method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: headers, // 设置请求的 header
success: function (res) {
//注意:可以对参数解密等处理
requestHandler.success(res)
},
fail: function () {
requestHandler.fail()
},
complete: function () {
// complete
}
})
}
/*获取列表封装*/
function store_list(url,params,sus) {
附上util.js 即,外来的js文件
封装的request不能放在app.js里.否则执行顺序app.js执行最晚,什么原因没查到.若有大牛知道请指教,故封装为一个js文件引入
var token;
wx.getStorage({
// wx.getStorageSync({
key: \'token\',
success(res) {
token = res.data.token
}, fail(res) {
console.log(\'1\')
token = \'\'
}, complete(res) {
store(url,params,sus)
}
})
}
var store = function store(url,params,sus){
var headers;
var method=\'POST\';
headers = {
\'content-type\': method == \'POST\' ?
\'application/x-www-form-urlencoded\' : \'application/json\',
\'stkjtoken\': token
}
wx.request({
url: API_URL + url,
data: params,
method: \'POST\', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: headers, // 设置请求的 header
success:sus.success,
fail:sus.fail,
complete: sus.complete
})
}
module.exports = {
GET: GET,
POST: POST,
store_list:store_list
}
附上小程序js封装文件路径及引用方式
常规ajax封装
请求数据列表..参数三个,分别是路径 .要传的参,以及成功回调函数