微信小程序的请求的封装

global.$ajax $ajax 只是自己取的名字,可自己取

	global.$ajax = function (url, data = {}, options = {}) {
	  return new Promise((resolve, reject) => {
	  	//设置请求的类型,默认  post
	    var method = options.type || "post";
	    if (global.state.ajaxNum <= 0) {
	    //导航栏显示正在刷新的图样
	      wx.showNavigationBarLoading();
	    }
	    //获取token
	    var user_token = global.state.token ? global.state.token : '';
	    wx.request({
	      url: global.state.baseUrl + url,//global.state.baseUrl 是我定义的全局的基础变量
	      data: data,
	      method: method,
	      header: {
	        // 'Content-Type': 'application/x-www-form-urlencoded',
	        // 'Content-Type': 'application/json',
	        'token': user_token || ''
	      },
	      success: res => {
	        console.log(res)
	        if (res.data.result !== null && res.data.result !== undefined && res.data.result.isLogin === false) {
	          if (wx.getStorageSync("authorizedCount") == 1){ //用于处理与loginWxAuth.js的授权的重复提示
	            return;
	          } else {
	            wx.setStorageSync("authorizedCount", 1)
	          }
	          wx.showModal({
	            title: '授权提示',
	            content: '您还未授权,请点击前往授权页面进行授权',
	            success: (res) => {
	              if (res.confirm) {
	                wx.navigateTo({
	                  url: '/pages/authorized/authorized'
	                })
	              } else if (res.cancel) {
	                wx.navigateBack({
	                  delta: 1,//这是回到上一级页面并带参数
	                })
	              }
	            },
	            complete:(res)=>{
	              wx.setStorageSync("authorizedCount", 0)
	            }
	          })
	         return  
	        }
	        resolve(res)
	      },
	      fail: err => {
	        reject(err);
	        wx.hideLoading();
	        wx.showToast({
	          title: '请求超时,请刷新重试~',
	          icon: 'none'
	        })
	      },
	      complete: () => {
	        global.state.ajaxNum = global.state.ajaxNum - 1;
	        if (global.state.ajaxNum <= 0) {
	          wx.hideLoading();
	          wx.hideNavigationBarLoading();
	          wx.stopPullDownRefresh();
	        }
	      }
	    });
	  })
	}
发布了50 篇原创文章 · 获赞 4 · 访问量 1276

猜你喜欢

转载自blog.csdn.net/weixin_43910427/article/details/104473586
今日推荐