微信小程序写一个请求接口函数

var getAjax = function(options){
  wx.getNetworkType({   //获取网络类型
    success: function (res) {
      // 返回网络类型, 有效值:
      // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
      if(res.networkType == 'none'){
        showModal("网络已断开,请联网后重试!",function(){
          if(options.complete){
            options.complete();
          }
        });
      }else{
        if (wx.showLoading) {
          wx.showLoading({
            title: '加载中',  
          })
        }
        if (options.token) {
          var _header = {
            'content-type': 'application/json',
            'Cookie': 'JSESSIONID=' + options.token
          };
        } else {
          var _header = {
            'content-type': 'application/json'
          }
        }
        return wx.request({
          url: baseUrl + options.url,
          data: options.params,
          method: options.method ? options.method : 'GET',
          success: options.success,
          header: _header,
          fail: function (res) {
            if (options.fail) {
              options.fail(res)
            }
          },
          complete: function () {
            if (wx.hideLoading) {
              setTimeout(function () {
                wx.hideLoading()//关闭提示
              }, 400);
            }
            if (options.complete) {
              options.complete();
            }
          }
        });
      }
    },
    fail:function(res){
      console.log("获取网络状态失败:",res);
    }
  });
}
 
showModal(cnt,fn);为自己写的一函数,用于显示弹窗,cnt为要显示的内容,fn为点击确定按钮执行的函数,有则执行。
if (wx.hideLoading)与if(wx.showLoading) 用于判断是否支持这个api
posted @ 2017-10-25 10:59  apgy  阅读(1373)  评论(0编辑  收藏  举报