发布于 2017-06-06 23:38:30 | 115 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的微信小程序入门,程序狗速度看过来!

小程序 微信小程序

微信小程序(weixinxiaochengxu),简称小程序,缩写XCX,英文名mini program,是一种不需要下载安装即可使用的应用,它实现了应用“触手可及”的梦想,用户扫一扫或搜一下即可打开应用。


这篇文章主要介绍了微信小程序封装http访问网络库实例代码的相关资料,需要的朋友可以参考下

微信小程序封装http访问网络库实例代码

之前都是使用LeanCloud为存储,现在用传统API调用时做如下封装

文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-request.html

代码如下:


var HOST = 'http://localhost/lendoo/public/index.php/';
// 网站请求接口,统一为post
function post(req) { 
//发起网络请求
 wx.request({
 url: HOST + req.uri, 
 data: req.param, 
 header: {
   "content-type": "application/x-www-form-urlencoded"
 },
 method: 'POST', 
 success: function (res) {
  req.success(res.data)
 }, 
 fail: function (res) {
   console.log(res);
 }
 })
}
// 导出模块
module.exports = { post: post
}

然后前端调用就可以这样做了:


var http = require('../../utils/http.js');
...
 http.post({ 
  uri: http.orderListUri, 
  param: {
   third_session: wx.getStorageSync('third_session')
  },  
   success: function (data) {
   that.setData({
    orderList: data
  });
  }
 });

一般对自己写的接口给自己用的时候,method方法或header都是约定好的,所以不用重复书写。


header: {
   "content-type": "application/x-www-form-urlencoded"
  },
method: 'POST'

而fail回调方法也可以统一处理;进一步地,也可以对success回调里的针对code值进一步判断,特定错误码统一处理,比如跳转登录页面等。

经过上述处理,是不是变得简洁了?

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务