**絕大多數場景請使用 encodeURIComponent()**。僅在需要編碼完整 URL 且保留結構字符(如 : / ? #)時使用 encodeURI()。
| 函數 | 編碼範圍 | 保留字符(不編碼) | 典型用途 |
|---|---|---|---|
encodeURIComponent | 單個參數值 | A-Z a-z 0-9 - _ . ! ~ * ' ( ) | 查詢參數、POST 數據、Hash 片段 |
encodeURI | 完整 URL | 上述 + ; , / ? : @ & = + $ # | 整體 URL 轉傳、重定向 |
escape (已棄用) | 不推薦 | 不同 | 舊代碼兼容 |
var baseUrl = 'https://api.example.com/search';
var keyword = '咖啡 & 茶'; // 含空格、特殊符號
var category = '飲品/熱飲'; // 含斜杠
// 正確:分別編碼每個參數值
var url = baseUrl + '?q=' + encodeURIComponent(keyword)
+ '&cat=' + encodeURIComponent(category);
// 結果: https://api.example.com/search?q=%E5%92%96%E5%95%A1%20%26%20%E8%8C%B6&cat=%E9%A3%B2%E5%93%81%2F%E7%83%AD%E9%A3%B2
// ❌ 錯誤:參數值中的 &、=、/ 會被保留,導致服務端解析錯誤
var badUrl = encodeURI(baseUrl + '?q=' + keyword + '&cat=' + category);
// 結果: ...q=咖啡 & 茶&cat=飲品/熱飲 (空格變 %20,但 & 和 / 未編碼)
decodeURIComponent(encodeURIComponent(str)) // 還原參數值
decodeURI(encodeURI(url)) // 還原完整 URL
// 原生 form 提交:瀏覽器自動按 application/x-www-form-urlencoded 編碼
// 手動拼接 AJAX 數據時:
var data = 'username=' + encodeURIComponent(userInput)
+ '&password=' + encodeURIComponent(passInput);
// jQuery $.param 內部已處理編碼
$.ajax({
url: '/login',
data: { username: userInput, password: passInput }, // 直接傳對象,jQuery 自動 encodeURIComponent
method: 'POST'
});
%2520 這類亂碼。前端編碼一次,後端解碼一次。encodeURIComponent 將空格編為 %20;舊規範 application/x-www-form-urlencoded 規定空格為 +。現代後端框架(Spring、Express、Django)均支援 %20,無需手動替換。encodeURIComponent('😀') 正確輸出 %F0%9F%98%80(UTF-8 字節序列)。記住口訣:「參數值用 Component,整體 URL 用 URI」。現代前端開發中,配合 URLSearchParams 或框架內置序列化,極少需手動調用編碼函數,但理解其原理對排查編碼亂碼問題至關重要。