微信小程序页面跳转url传参,对象、数据过长、特殊字符问题

1、传递参数为对象格式
若参数为对象则需先使用 JSON.stringify()进行转换 , 接收后使用JSON.parse()转为对象.

但这样传参有一个问题,当对象数据长度过大时会报错,因为url传参时程序把过长的那段数据给截取掉了,导致数据转换回来时格式不对而报错。

2、传递参数中含有? = &等特殊字符
若传递参数中含有=,?,&等特殊字符,无法正常传递参数,则需要进行编码解码。

解决:
这时可以再添加另一个API:encodeURIComponent(obj) 和 decodeURIComponent(options.obj),在encodeURIComponent之前要用JSON.stringify()先转换数据,decodeURIComponent之后再用JSON.parse()转换回来。

encodeURIComponent(JSON.stringify(obj))为跳转url时的转换方法。

JSON.parse(decodeURIComponent(options.obj))为接收参数页面的转换方法。

例如:

// 传递页
wx.navigateTo({
    
    
     url: '../info/info?url=' +  encodeURIComponent(JSON.stringify(e.currentTarget.dataset.url))
})

// 接收页
onLoad: function (options) {
    
    
   this.setData({
    
    
     url : JSON.parse(decodeURIComponent(options.url))
   })
},

猜你喜欢

转载自blog.csdn.net/joe0235/article/details/122077855
今日推荐