封装代码引入全局里面,其他页面引入调用即可
//封装微信小程序网络i请求的全局方法
// url 请求地址
// method get还是post 这里要求大写
// data 传值 不传值写null或者{}
// callback 网络请求成功之后的回调函数
//errFn 请求失败的回调函数 不传的话一定要给个函数
//comFn 请求失败或者成功的回调 不传的话一定要给个函数
reqHttp(url,method,data,callback,errFn,comFn){
wx.request({
url:url,
method:method,
data:data,
header:{
//三元运算判断是post请求还是get请求
"content-type":method == "GET"? "json":"application/x-www-form-urlencoded"
},
success:(res)=>{
callback(res);//回调函数
},
fail:()=>{
errFn;
},
complete:()=>{
comFn
},
})
},//先引入
let app = getApp();
//网址请求
getGroupCity(){
//调用全局的网络请求
app.reqHttp("https://elm.cangdu.org/v1/cities?type=group",
"GET",
{},
this.succ,
this.fail,
this.comFn);
},
//网址请求响应回来的数据
succ(data){
console.log(data)
},
//网址请求失败的函数
fail(){},
//失败成功都执行的函数。比如关闭加载页面
comFn(){},POST
let app = getApp();
getGroupCity(){
//调用全局的网络请求
app.reqHttp("https://elm.cangdu.org/v1/cities?type=group",
"POST",
{},
this.succ,
this.fail,
this.comFn);
},
succ(data){
console.log(data)
},
fail(){},
comFn(){},然后自己放到onLoad调用
onLoad: function (options) {
this.getGroupCity();
}上一篇:小程序获取input值的方法
下一篇:setData性能问题如何优化