背景:在使用微信小程序的 wx.navigateTo方法进行页面跳转传参时,使用JSON.stringify序列化,子页面接收参数时报错SyntaxError: Unexpected end of JSON input
原因:传递参数通常是通过 URL 的查询字符串来实现的。然而,直接传递 JSON 对象作为查询参数时,由于 URL 的限制(例如,长度限制和特殊字符的限制),直接传递 JSON 对象可能会导致数据被截断或者编码不正确,从而导致解析失败
我的项目是使用了特殊字符?导致数据被截断
解决方法:
使用encodeURIComponent 和 decodeURIComponent
使用encodeURIComponent 对字符串进行编码,子页面接收参数时用decodeURIComponent解码
父页面
wx.navigateTo({
url:`../audioCont/index?item=${encodeURIComponent(JSON.stringify(item))}`
})
子页面
onLoad(options) {
const items = !!options.item?JSON.parse(decodeURIComponent(options.item)):''
}