超好用超短的小程序請求封裝

超好用超短的小程序請求封裝,也不算特別特別短吧哈哈哈。但真的很好用的一個小程序請求封裝,在請求的時候簡短提升效率不須要將同樣的東西重複寫。下面就讓你們看看這個封裝是有多短,不夠短的話也請別打我javascript

網上多數使用的小程序封裝是在單獨的一個js文件,再使用module.exports進行輸出方法。我所介紹的封裝方法有殊途同歸之妙,只不過是寫在app.js裏邊,省去了使用時必須引用文件的麻煩。html

app.jsjava

xcxPost(options = {}) { wx.showLoading({ mask: true, title: '', }) wx.request({ url: this.globalData.postUrl + options._url, data: options._data || {}, method: "POST", dataType: "json", header: this.globalData.header, success: (res) => { if (res.data.errcode > 0) { if (typeof options._success == "function") { options._success(res.data); } } else { this.xcxErrorToast({ title: res.data.errmsg || '服務器返回錯誤!' }); return; } }, fail: (res) => { if (typeof options._fail == "function") { options._fail(res); } if (typeof options._fail == "string") { //請求失敗的彈框提示
          wx.showToast({ title: options._fail, icon: 'loading', duration: 2000 }); } }, complete: (res) => { if (typeof options._complete == "function") { options._complete(res); } wx.hideLoading() } }); },

此處的this.globalData,是在app.js設置的,也就是小程序的全局屬性,不瞭解的朋友請查閱小程序官方文檔json

而以上封裝具體的返回參數說明,請移步官方文檔   https://developers.weixin.qq.com/miniprogram/dev/api/network-request.html#wxrequestobject小程序

App({ globalData:{ userInfo:{},
    postUrl: (wx.getExtConfigSync().request_url || '(後臺接口地址)'), header: { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': '' },
  },

 

其餘頁面引用封裝請求,好比 index.jsapi

/** * http請求 * 得到banner圖 */ getShopId(callBack) { app.xcxPost({ _url:'pc_home_page/banner',// 你須要發起的請求; _data: { type: '1' },// 你須要傳的請求參數; _success: (resp) => {//請求成功後的操做;if (resp.errcode > -1) { // this.globalData.shopId = resp.list.shopId; // this.globalData.domainUrl = resp.list.domain;
          if (callBack) { callBack() } } }    }) },
相關文章
相關標籤/搜索