目標要求:
實現從A頁面跳轉至B頁面,B頁面接收A頁面通過地址欄傳遞過來的中文參數,中文不能出現亂碼。
A頁面部分代碼(傳遞參數):
var title = "這是中文"; var t = encodeURI(encodeURI(title)); window.location.href = "b.html?title=" + t;
B頁面部分代碼(接收參數):
var t = GetQueryString("title"); //獲取地址欄參數
var title = decodeURI(t); //只需要轉一次碼
// 利用正則表達式方式,獲取地址欄中的的參數值
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;
}
關鍵方法講解:
1. encodeURI() 函數可把字符串作為URI進行編碼
2. decodeURI() 函數可對encodeURI()函數編碼過的URI進行解碼
經過實測IE,Chrome,Fire Fox 等主流瀏覽器均沒問題
