JS 獲取url引數以及中文亂碼問題
阿新 • • 發佈:2018-12-17
encodeURI() 函式可把字串作為 URI 進行編碼
var para=window.location.search;// 當前請求的url的引數部分
console.log(para) // 結果 ?name=%E5%90%8D%E7%A7%B0&type=%E7%B1%BB%E5%9E%8B
- 獲取指定引數
//根據引數部分和引數名來獲取引數值 function getParamString(paraPart,name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = paraPart.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } function getParamFromUrl(name){ var r = getParamString(window.location.search,name) return r }
- 中文亂碼問題 在上面的結果中可以看到這裡中文已經被encodeURI編碼了 所以我們需要decodeURI
var msg =decodeURI(getParamFromUrl('name'))
console.log(msg) // å称
仍然出現亂碼,這是英文在url我們需要輸入編碼後的地址而且需要編碼兩次
- 編碼一次
encodeURI('http://a.com/index.html?name=名稱&type=型別')
// http://a.com/index.html?name=%E5%90%8D%E7%A7%B0&type=%E7%B1%BB%E5%9E%8B
輸入到瀏覽器時還是編碼前的
- 編碼兩次
encodeURI(encodeURI('http://a.com/index.html?name=名稱&type=型別'))
// http://a.com/index.html?name=%25E5%2590%258D%25E7%25A7%25B0&type=%25E7%25B1%25BB%25E5%259E%258B
因為瀏覽器位址列會進行編碼為中文所以需要編碼兩次到瀏覽器位址列