微信小程序 路由跳转传参wx.navigateTo ,字符串转对象报错

官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html

(一)问题

 

看了文档之后,传一个参数没有问题,就是如果你路由跳转想传对象,必须将对象转换成字符串,

JSON.stringify()

当后台数据 较复杂的时候,比如传了个富文本格式的字符串

A页面将其转换成字符串,B页面进行接收

//A页面传参    item是对象
var detailsData= JSON.stringify(item);
wx.navigateTo({
      url:'/pages/plaza/project_intro/project_intro?detailsData='+detailsData
    })

B页面接收参数,console打印发现 字符串好像被截断了许多

  onLoad: function (options) {
    console.log(options);
  }

  onLoad: function (options) {
    var detailsDataObj = JSON.parse(options.detailsData);
    console.log(detailsDataObj);
  }

将其转换成对象就会报错。。。

(二)解决

看了其他博文说是,由于对象中包含 url 属性,JSON.parse 方法无法解析包含“?“、”&”之类的字符

最后试了一下 通过js的一个方法进行编码解码。

encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。

A页面进行 编码再传参

var detailsData= JSON.stringify(item);
//直接转字符串 ,在下个页面转对象的时候会报错,不知道是长度限制还是字符串有问题,所以使用encodeURIComponent转码
detailsData = encodeURIComponent(detailsData);
wx.navigateTo({
     url:'/pages/plaza/project_intro/project_intro?detailsData='+detailsData
  })

B页面进行 解码再读取参数

  onLoad: function (options) {
    console.log(options);
    var detailsDataStr = decodeURIComponent(options.detailsData);
    var detailsDataObj = JSON.parse(detailsDataStr);
    console.log(detailsDataObj);
  }

console 成功打印出参数

如果有更好的解决办法,欢迎评论留言哦!!!

猜你喜欢

转载自blog.csdn.net/u012302552/article/details/83309264
今日推荐