1. 微信小程序 wx.request方法的异步封装实例详解
wx-promise-request 是对微信小程序 wx.request 方法的异步封装。
解决问题:
支持Promise(es6-promise)。管理请求队列,解决 request 最大并发数超过 10 会报错的问题。
下载:npm
install
wx-promise-request
然后拷贝 dist/index.js 文件到你的小程序项目中。
1 import {request} from './wx-promise-request'; 2 request({ 3 url: 'test.php', 4 data: { 5 x: '', 6 y: '', 7 }, 8 header: { 9 'content-type': 'application/json', 10 }, 11 }) 12 .then(res => console.log(res)) 13 .catch(error => console.error(error))
API
setConfig(object)
通过 setConfig 配置 wx-promise-request,如:使用 qcloud 提供的 request 方法;使用其他 Promise 库等等。
1 import {request, setConfig} from './wx-promise-request'; 2 import qcloud from './vendor/qcloud-weapp-client-sdk/index'; 3 import Promise from 'bluebird'; 4 5 setConfig({ 6 request: qcloud.request, 7 Promise, 8 }) 9 request({ 10 url: 'test.php', 11 }) 12 .then(res => console.log(res)) 13 .catch(error => console.log(error));
2. 页面跳转(传参)
<view class="btn-area"> <navigator url="../navigator/navigator?title=我是navigate" >跳转到新页面</navigator> <navigator url="../redirect/redirect?title=我是redirect" redirect>在当前页打开</navigator> </view></span>
index.wxml中的URL就是跳转的页面路径.上面代码中就是navigator目录下的navigator页面,title是参数.
navigator下redirect属性是值在当前页打开.如果不加redirect就是跳转到新页面.都可以携带参数.
1 获取参数: 2 Page({ 3 onLoad: function(options) { 4 this.setData({ 5 title: options.title 6 }) 7 } 8 })
小程序跳转、请求、带参数请求小例子:
* wx.request(OBJECT)
wx.request发起的是 HTTPS 请求。一个微信小程序,同时只能有5个网络请求连接。
1 //当页面加载时,请求后台数据,并赋值给前台显示 2 Page({ 3 data:{ 4 new_list:[] 5 }, 6 onLoad:function(){ 7 var that = this; 8 wx.request({ 9 url:'http://wxcms.com/getList', 10 header:{ 11 'content-type':'application/json', 12 }, 13 success:function(res) 14 { 15 //将请求的后台数据赋值new_list 16 that.setData({ 17 new_list:res.data, 18 }) 19 } 20 }) 21 } 22 })
保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。
wxml:
1 <view class="lists"> 2 <view class="img"> 3 <!---这里绑定了一个手指触摸后马上离开的时间,跳转时并带上了id参数--> 4 <image src="{{img}}" bindtap="detial" data-id="{{id}}"></image> 5 </view> 6 <view class="info"> 7 <view class="title">{{title}}</view> 8 <view class="time">{{time}}</view> 9 </view> 10 </view>
js:
1 Page({ 2 data:{ 3 new_list:[] 4 }, 5 detial:function(event){ 6 //带id跳转到指定的页面,这里的event.target.dataset.id是获取wxml页面上的data-id参数,详见事件说明 7 wx.navigateTo({ 8 url:"../../pages/detail/detail?id="+event.target.dataset.id 9 }) 10 } 11 })
*带参数的wx.request(OBJECT)
上述代码跳转到指定页面后:
1 Page({ 2 data:{ 3 info:{} 4 }, 5 //res对象包含了跳转页面中的id参数,再页面加载时,获取id参数然后向后台请求参数,并赋值 6 onLoad:function(res) 7 { 8 var that = this; 9 wx.request({ 10 url:"http://wxcms.com/getOne", 11 //这里是 12 data:{ 13 id:res.id, 14 }, 15 header:{ 16 'content-type':'application/json' 17 }, 18 success:function(msg) 19 { 20 that.setData({ 21 info:msg.data, 22 }) 23 } 24 }) 25 } 26 })