小程序封装一个ajax

小程序中,我们一般习惯把提交接口请求的方法放在一个公共js里面。下面是一个简单实现。

(1)我们把所有请求的地址都放在一个json里面

var postAddress = {
  "domin": "http://www.baidu.com",    //域名
  "getOpenId": "/index/getOpenId", //登录获取用户信息
  "orderlist": "/business/orderlist",
  "orderdetail": "/business/orderdetail",
  "initOrder": "/order/init"
};

(2)封装wx.request

function post(postName, paramData = {}, callback) {
  var data = {token: token};  //添加公共数据,比如token
  for (var key in paramData) {
    data[key] = paramData[key];
  }
  var reqUrl = postAddress ['domin'] + postAddress [postName];
  if (reqUrl) {
    wx.request({
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      url: reqUrl,
      data: data,
      success: function (res) {
        if (callback != '') {
          callback(res);
        }
      }, fail: function (res) {
        console.log(JSON.stringify(res));
      }
    })
  }
}

(3)对外提供方法

module.exports = {
  post: post
}

(4)使用

  在app.js中引入post.js

const util = require("./utils/post.js");
App({
  onLaunch: function () {
     wx.login({
      success: res => {
        if (res.code) {
          util.post("getOpenId", {code: res.code}, function(ret){
            if(ret.data.code == 200){
              //获取openId成功
            }
          });
        }
      }
  }
})

也可以将util保存到app里面,在pages页面使用,直接引用app即可。

const app = getApp()

猜你喜欢

转载自www.cnblogs.com/greys/p/10730877.html