微信小程序之跳转、请求、带参数请求小例子

wx.request(OBJECT)

wx.request发起的是 HTTPS 请求。一个微信小程序,同时只能有5个网络请求连接。 
具体参数说明参看微信小程序官方文档-发起请求。 
例:

//当页面加载时,请求后台数据,并赋值给前台显示
Page({
    data:{
        new_list:[]
    },
    onLoad:function(){
        var that = this; wx.request({ url:'http://wxcms.com/getList', header:{ 'content-type':'application/json', }, success:function(res) { //将请求的后台数据赋值new_list that.setData({ new_list:res.data, }) } }) } })



wx.navigateTo(OBJECT)

保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 
具体参数说明参看微信小程序官方文档-跳转

例: 
wxml代码:

<view class="lists"> <view class="img"> <!---这里绑定了一个手指触摸后马上离开的时间,跳转时并带上了id参数--> <image src="{{img}}" bindtap="detial" data-id="{{id}}"></image> </view> <view class="info"> <view class="title">{{title}}</view> <view class="time">{{time}}</view> </view> </view>


js代码:

Page({
    data:{
        new_list:[]
    },
    detial:function(event){
        //带id跳转到指定的页面,这里的event.currentTarget.dataset.id是获取wxml页面上的data-id参数,详见事件说明
        wx.navigateTo({
            url:"../../pages/detail/detail?id="+event.currentTarget.dataset.id }) } })




带参数的wx.request(OBJECT)

上述代码跳转到指定页面后:

Page({
    data:{
        info:{}
    },
    //res对象包含了跳转页面中的id参数,再页面加载时,获取id参数然后向后台请求参数,并赋值
    onLoad:function(res)
    {   
        var that = this; wx.request({ url:"http://wxcms.com/getOne", //这里是传参res.id就是跳转url(?id=xxxx)的参数值 xxxx data:{ id:res.id, }, header:{ 'content-type':'application/json' }, success:function(msg) { that.setData({ info:msg.data, }) } }) } })

猜你喜欢

转载自www.cnblogs.com/lynna/p/9155941.html