最近,在js原生開發(fā)中,利用url地址傳參,有時會遇到亂碼的問題,以下針對這個問題進(jìn)行詳解。
1.列表頁傳參
// url傳參 encodeURI()編碼
var Parameter = '供水設(shè)備系列';
$('.parBd ul li a').click(function () {
window.location.href =
'./product_detail.html?location=' + encodeURI(Parameter);
});
2.詳情頁接收url的參數(shù),并且解析:decodeURI()解碼
// 獲取url 傳參
function GetRequest() {
var url = decodeURI(location.search); //獲取url中"?"符后的字串 并且解析Url編碼
var theRequest = new Object();
if (url.indexOf('?') != -1) {
var str = url.substr(1);
strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
}
}
return theRequest;
}
var locationVal = new Object();
locationVal = GetRequest();
var MatchId = locationVal['location'];
console.log(MatchId);//獲取到參數(shù)值
解釋一下上面的代碼:
1.decodeURI()和encodeURI()用于解碼和編碼URL的倆個JS函數(shù)
2.substr(1) 相當(dāng)于 substring(1,str.length)
3.unescape()對不是英文字母進(jìn)行解碼
這樣參數(shù)就拿到了~~~~,可以用這個參數(shù)調(diào)接口了