小程序自带的网络请求,如图下:
在一个程序中网络请求是必须的,如果按照他的这个样式写,肯定代码多的不得了,所以我们将其进行一个简单的封装,
话不多说直接切入正题:
网络请求的样式
如何使用:
1.首先要进行对我的工具类进行引入:
2.调用方法
3.如果你后台想要表单的格式 或者是 json格式,改变头里的Content-Type类型
表单的格式:
json格式:
工具类的代码如下
//添加请求根目录
var rootDocment =
"http://192.168.10.103:8081";
function goPost(url, data, cb) {
wx.request({
url: rootDocment + url,
data: data,
method:
'post',
header: {
'Content-Type':
'application/x-www-form-urlencoded' },
success:
function (res) {
return
typeof cb ==
"function" && cb(res.data)
},
fail:
function () {
return
typeof cb ==
"function" && cb(
false)
}
})
}
function getDataKey(){
return
""
}
function goGet(url, data, cb) {
wx.request({
url: rootDocment + url,
data: data,
method:
'get',
header: {
'Content-Type':
'application/x-www-form-urlencoded' },
success:
function (res) {
return
typeof cb ==
"function" && cb(res.data)
},
fail:
function () {
return
typeof cb ==
"function" && cb(
false)
}
})
}
module.exports = {
goPost: goPost,
getDataKey: getDataKey,
goGet: goGet,
}
此网络请求工具类完成。