小程序请求接口数据封装

原创 2018-11-16 09:38:13 268
摘要:var requestUrl = "https://www.admin.com/";var AppID = 'AppID ';var AppSecret = 'AppSecret ';function post(url, data, fun, that) {if (url == 'undefined') {re

var requestUrl = "https://www.admin.com/";

var AppID = 'AppID ';

var AppSecret = 'AppSecret ';

function post(url, data, fun, that) {

if (url == 'undefined') {

return false;

}

var postUrl = requestUrl + url;

wx.request({

url: postUrl,

data: data,

method: "POST",

dataType: "json",

header: {

'content-type': 'application/json' // 默认值

},

success: function (res) {

that[fun](res.data.result);

},

fail: function (res) {

console.log('请求失败,请重试');

return {};

}

})

}

function login(url, data, fun, that) {

if (url == 'undefined') {

return false;

}

wx.login({

success: function (res) {

wx.request({

url: 'https://api.weixin.qq.com/sns/jscode2session',

data: {

appid: AppID,

secret: AppSecret,

js_code: res.code,

grant_type: 'authorization_code'

},

method: "POST",

dataType: "json",

header: {

'content-type': 'application/json' // 默认值

},

success: function (res) {

console.log(res);

data.unionid = 1;

post(url, data, fun, that);

},

fail: function (res) {

console.log('获取用户信息失败!');

return {};

}

})

}

});

}

module.exports.post = post;

module.exports.login = login;

这个

that[fun](res.data.result);

fun是个形参?是指向调用的函数还是值?直接用console.log(res.data.result)可以吗?

 因为小程序不能把数据传回去,所以使用回调的方式把值传出去。

批改老师:查无此人批改时间:2018-11-16 09:55:58
老师总结:在方法里可以console.log, that[fun](res.data.result); that是调用这个方法的this。 [fun]是调用这个方法后,回调的方法。

发布手记

热门词条