小程序导航传递参数及接受时JSON.parse不能解析的解决办法

在小程序有时要在不同页面时传递大量数据时需要把传递参数用JSON.stringify()函数转成字符,在目标页面中用JSON.parse函数接收:
例子:在原始页面点击跳转,携带一个对象moment

{"shortcode":"Bkfe_1lAo3T",
 "caption":"I’m so proud to be part of the Biotherm Homme family. Follow @biothermhomme to discover my new exciting adventure  #BiothermHomme #AchieveMore  And thanks for my fans",
 "displayUrl":"/vp/159bc9142bc82e0db91776331ece838a/5BEAF44B/t51.2885-15/e35/35260743_194606054534470_6377703521738817536_n.jpg",
 "thumbnailUrl":"/vp/7381d0d0b009f7133d42e478309118cd/5BE65799/t51.2885-15/s640x640/sh0.08/e35/c0.135.1080.1080/35260743_194606054534470_6377703521738817536_n.jpg",
 "isVideo":false,
 "takenAt":"2 天前",
 "likedByCount":645421,
 "typename":"GraphSidecar",
 "ownerid":"1314058659",
 "username":"zyxzjs",
 "commentCount":0,
 "likedCount":0,
 "videoInfo":{},
 "sidecarInfo":null,
 "publisherInfo":{"id":"1314058659",
                  "username":"zyxzjs",
                  "fullName":"Lay Zhang",
                  "publishedCount":null,
                  "profilePicUrl":"/vp/71d90e2ff2781d5fafcef33efecdd123/5BC59F99/t51.2885-19/s150x150/13628117_1892759814284262_1673741476_a.jpg",
                  "displayName":"",
                  "biography":"Music Producer|Singer|Dancer|Actor",
                  "followedByCount":null,
                  "profilePicUrlHd":"/vp/9549935b351dc48fbd36ad5c7c26b386/5BC85181/t51.2885-19/s320x320/13628117_1892759814284262_1673741476_a.jpg",
                  "desc":""}
                  }
  previewImage: function (e) {
    let index = e.currentTarget.dataset.index;
    let moment = JSON.stringify(this.data.moment[index]);

    wx.navigateTo({
      url: '../moment_detail/moment_detail?moment=' + moment
    })
  },

在目标页面接收:

  onLoad: function(options) {
    let moment = options.moment

    this.setData({
      detail: JSON.parse(moment)
    })
  }

有时在解析接收对象时发生:

Unexpected end of JSON input;at pages/moment_detail/moment_detail page lifeCycleMethod onLoad function
SyntaxError: Unexpected end of JSON input

解决办法:

在JSON.stringify()之后将变量使用encodeURIComponent函数处理,encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。在目标页面接收时用decodeURIComponent转回字符串。
即:

  previewImage: function (e) {
    let index = e.currentTarget.dataset.index;
    let monent = JSON.stringify(this.data.moment[index]);

    wx.navigateTo({
      url: '../moment_detail/moment_detail?moment=' + encodeURIComponent(monent)
    })
  },

详细可见JavaScript encodeURIComponent() 函数

猜你喜欢

转载自blog.csdn.net/ruffaim/article/details/80841979