如何解決js地址欄中傳遞中文亂碼的問題
目標(biāo)要求:
實(shí)現(xiàn)從A頁面跳轉(zhuǎn)至B頁面,B頁面接收A頁面通過地址欄傳遞過來的中文參數(shù),中文不能出現(xiàn)亂碼。
A頁面部分代碼(傳遞參數(shù)):
var title = "這是中文";var t = encodeURI(encodeURI(title)); window.location.href = "b.html?title=" + t;
?
B頁面部分代碼(接收參數(shù)):
var
?t = GetQueryString(
"title"
);?
//獲取地址欄參數(shù)
var
?title = decodeURI(t);?
//只需要轉(zhuǎn)一次碼
?// 利用正則表達(dá)式方式,獲取地址欄中的的參數(shù)值
function
?GetQueryString(name) {
????
var
?reg =?
new
?RegExp(
"(^|&)"
?+ name +?
"=([^&]*)(&|$)"
);
????
var
?r = window.location.search.substr(1).match(reg);
????
if
(r !=?
null
)
????????
return
?unescape(r[2]);
????
return
?null
;
}
關(guān)鍵方法講解:
1. encodeURI()? ? 函數(shù)可把字符串作為URI進(jìn)行編碼
2. decodeURI()? ? 函數(shù)可對(duì)encodeURI()函數(shù)編碼過的URI進(jìn)行解碼
?
經(jīng)過實(shí)測IE,Chrome,F(xiàn)ire Fox 等主流瀏覽器均沒問題
鏈接:https://www.dianjilingqu.com/533925.html