首頁  >  文章  >  微信小程式  >  小程式實作post與get的封裝

小程式實作post與get的封裝

小云云
小云云原創
2018-01-31 14:21:242720瀏覽

本文主要和大家介紹微信小程式中post方法與get方法的封裝的相關資料,讓大家掌握如何封裝,需要的朋友可以參考下,希望能幫助到大家。

微信小程式開發post方法與get方法的封裝

#第一步:在utils資料夾下建立httpUtil.js檔案

第二步:建立函數httpPost方法程式碼如下:


function Post(url, data, cb, isShow, showNetError, that, showLoading) {
 if (showLoading == true || showLoading == undefined){
  wx.showNavigationBarLoading();
  wx.showLoading({
   title: '加载中...',
  })
 } 
 var basicData = {
  vloginPwd: api.vloginPwd,
  vtoken: api.vtoken
 }
 if (!isEmpty(data)) {
  for (var key in data) {
   try {
    basicData[key] = data[key];
   } catch (e) { }
  }
 }
 wx.request({
  url: url,
  header: { 'content-type': 'application/x-www-form-urlencoded' },
  method: 'POST',
  data: basicData,
  success: (res) => {   
   if (res.data.state == 200) {
    typeof cb == "function" && cb(res.data, "");
   } else {
    if (isShow == true) {
     wx.showModal({
      title: '提示',
      content: res.data.msg,
      showCancel: false      
     })
    }
   }
  },
  fail: (err) => {
   if (showNetError) {
    that.setData({
     errorDisplay:'',
     containHidden:true
    })
   }   
  },
  complete: (res) => {   
   setTimeout(function () {
    wx.hideNavigationBarLoading();
    wx.hideLoading();
   }, 100)  
  }
 });
};

第三步,在module裡加入:


module.exports = {
 httpGet: Get,
 httpPost: Post 
};

第四步,介紹


var httpUtil = require('../../utils/HttpHelper.js')

第五步,如何使用


onload:function(option){
  var that = this;
  httpUtil.httpPost(api.getListUrl, jsonData, function (res) {
   wx.showModal({
    title: '提示',
    content: res.msg,
    showCancel: false,
    confirmText:"查看",
    success: function (res) {
     console.log("res.data===", res.data);
     if (res.confirm) {
      that.toDetail(res.data);
     }
    }
   })
  }, true, true, this);
}

相關推薦:

Python中post與get方式提交資料的程式碼實例分享

淺析Jquery AJAX POST與GET之間的用法差異

PHP基礎之POST與GET

#

以上是小程式實作post與get的封裝的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn