在 JavaScript 中,傳遞 URL 參數時,如果參數包含中文字符,可能會出現亂碼問題。解決這一問題可以使用 encodeURIComponent 和 decodeURIComponent 函數。這些函數會對 URL 參數進行編碼和解碼,確保特殊字符(包括中文字符)能夠被正確傳遞和解析。
以下是一個完整的解決方案示例:
?1. 傳遞參數(編碼)
在傳遞 URL 參數時,可以使用 encodeURIComponent 對參數進行編碼:
javascript
// 中文參數
let param = "中文測試";
// 編碼參數
let encodedParam = encodeURIComponent(param);
// 構建URL
let url = https://example.com?param=${encodedParam};
console.log(url); ?// 輸出:https://example.com?param=%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95
?2. 接收參數(解碼)
在接收 URL 參數時,可以使用 decodeURIComponent 對參數進行解碼:
javascript
// 獲取URL參數
let urlParams = new URLSearchParams(window.location.search);
// 獲取并解碼參數
let decodedParam = decodeURIComponent(urlParams.get('param'));
console.log(decodedParam); ?// 輸出:中文測試
?示例代碼
下面是一個完整的示例,包括傳遞和接收中文參數:
html
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <title>URL Parameter Example</title>
</head>
<body>
? ? <script>
? ? ? ? // 示例傳遞參數
? ? ? ? let param = "中文測試";
? ? ? ? let encodedParam = encodeURIComponent(param);
? ? ? ? let url = https://example.com?param=${encodedParam};
? ? ? ? console.log("Encoded URL: " + url); ?// 輸出編碼后的URL
? ? ? ? // 示例接收參數(假設當前URL包含參數)
? ? ? ? let currentUrlParams = new URLSearchParams(window.location.search);
? ? ? ? let receivedParam = decodeURIComponent(currentUrlParams.get('param'));
? ? ? ? console.log("Decoded Parameter: " + receivedParam); ?// 輸出解碼后的參數
? ? </script>
</body>
</html>