页面跳转时出现“SyntaxError:Unexpected end of JSON input
”错误的原因是因为JSON的解析出现了错误
解决办法
在跳转页面先将数组或对象转换用JSON.stringify转换为字符串然后再用encodeURIComponent对字符串进行编码。
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( ) 。
其他字符(比如 :;/?😡&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。
const info = JSON.stringify(e.currentTarget.dataset.item);
wx.navigateTo({
url: '../detail/detail?info=' + encodeURIComponent(info),
});
然后再跳转后的页面先进行decodeURIComponent对encodeURIComponent() 进行解码,然后再JSON.parse恢复为数组或者对象
decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
this.setData({
info: JSON.parse(decodeURIComponent(options.info))
})