记录一个看似很难的Bug:url 请求自动编码格式,应该是字符串的地方显示”%5Bobject%20Object%5D“;
后台传参:
exampleSingle.put("goods_id", goodsId);
exampleList.add(exampleSingle);
//前台取值
<li v-for="goodsInfo in goodsList"> <div class="userbc"> <div class="qpop-user" :style="{backgroundImage:'url(' + goodsInfo.goods_image + ')',backgroundRepeat:'no-repeat',backgroundPosition:'left center'}"></div> </div> <div class="pop-center"> <p class="pop-text01">{{goodsInfo.goods_name}}</p> <p class="pop-text02">{{goodsInfo.goods_desc}}</p> </div> <div class="popbtnfix"> <span class="pop-btn-order" v-tap="buyRecommendGood(goodsInfo)">立即订购</span> </div> </li>
组装要跳转的url:
buyRecommendGood: function (goodsInfo) { console.log("组装前的goods_id:"+ goodsInfo.goods_id); this.currentBuyGoodsId = goodsInfo.goods_id; this.goodsUrl = goodsInfo.goods_url; WebView.open(rootVM.buyRecommendGoodsUrl); },
buyRecommendGoodsUrl: function() { console.log("跳转推荐商品的的URL:"+this.goodsUrl + "?goodsId=" + this.currentBuyGoodsId + "&shopId=" + this.shopId + "&qrcodeId=" + this.qrcodeId + "&from=fansCenter"); return this.goodsUrl + "?goodsId=" + this.currentBuyGoodsId + "&shopId=" + this.shopId + "&qrcodeId=" + this.qrcodeId + "&from=fansCenter"; }
按照正常逻辑来讲,要跳转的url里goodsId的值应该是哥字符串,但是在产品转测之后,有测试反应会出现乱码情况:
测试怀疑是我传值有问题,我也很郁闷,因为觉得逻辑怎么样都不应该有问题的,
百度了一下url编码解码,将”%5Bobject%20Object%5D“解码之后发现是个[Object Object];
因此对自己代码产生了怀疑,甚至在代码里加了日志打印(如上图)
后来结合之前的代码综合分析,因为我们页面和js是分开的,因此在html更新之后,加载了新的页面,js使用的依旧是缓存里的,所以导致传的值是[Object Object]类型,url请求的时候自动编码了,因此显示了“%5Bobject%20Object%5D”
在此贴出之前的代码,便于大家理解,
HTML部分:
<li v-for="goodsInfo in goodsList"> <div class="userbc"> <div class="qpop-user" :style="{backgroundImage:'url(' + goodsInfo.goods_image + ')',backgroundRepeat:'no-repeat',backgroundPosition:'left center'}"></div> </div> <div class="pop-center"> <p class="pop-text01">{{goodsInfo.goods_name}}</p> <p class="pop-text02">{{goodsInfo.goods_desc}}</p> </div> <div class="popbtnfix"> <span class="pop-btn-order" v-tap="buyRecommendGood(goodsInfo.goods_id)">立即订购</span> </div> </li>
js部分:
buyRecommendGoodsUrl: function() { return this.woYiShouLink + "?goodsId=" + this.currentBuyGoodsId + "&shopId=" + this.shopId + "&qrcodeId=" + this.qrcodeId + "&from=fansCenter"; }
buyRecommendGood: function (buyGoodsId) { this.currentBuyGoodsId = buyGoodsId; WebView.open(rootVM.buyRecommendGoodsUrl); },
后台传值方式不变;
虽然是一个清了缓存就OK的低级Bug,但是在前后台交互,尤其是发url请求的时候,最好在发送请求的时候加上编码:
个人推荐用:encodeURI()或者encodeURIComponent()
encodeURI()是Javascript中真正用来对URL编码的函数。
编码整个url地址,但对特殊含义的符号"; / ? : @ & = + $ , #",也不进行编码。对应的解码函数是:decodeURI()。
encodeURIComponent()
能编码"; / ? : @ & = + $ , #"这些特殊字符。对应的解码函数是decodeURIComponent()。
如果想要传递带&符号的网址,用encodeURIComponent()
推荐一个在线 解码编码的:http://tool.chinaz.com/Tools/urlencode.aspx
打完收工;