在 AJAX 請求中,若參數值包含 + 號(如電影名稱「B+偵探」),直接傳遞會導致後端接收到的字串將 + 解析為空格,造成查詢失敗或連結錯誤。
+ 在 application/x-www-form-urlencoded 內代表空格。+ 進行 %2B 編碼,伺服器會誤判為空格。encodeURIComponent(推薦)const param = "B+偵探";
const encoded = encodeURIComponent(param); // "B%2B%E5%81%B5%E6%8E%A2"
// 發送時帶入 encoded 值
.param() 自動處理$.ajax({
url: "/api/search",
data: { keyword: "B+偵探" }, // jQuery 內部會自動 encodeURIComponent
// 或
data: $.param({ keyword: "B+偵探" })
});
URLDecoder.decode(param, "UTF-8")urldecode($param) 或自動由 $_GET/$_POST 處理querystring.parse 或 decodeURIComponenturllib.parse.unquotefunction searchMovie(name) {
const safeName = encodeURIComponent(name);
$.get(`/api/movie?name=${safeName}`, function(res) {
console.log(res);
});
}
// 或使用 data 物件讓 jQuery 自動編碼
function searchMovie2(name) {
$.ajax({
url: "/api/movie",
data: { name: name }, // 內部自動 encode
success: function(res) { console.log(res); }
});
}
| 字元 | 編碼後 | 備註 |
|---|---|---|
| 空格 | %20 | 或 +(僅限 form-urlencoded) |
| # | %23 | 片段識別符 |
| & | %26 | 參數分隔符 |
| = | %3D | 鍵值分隔符 |
| ? | %3F | 查詢字串起始 |
| % | %25 | 編碼標記本身 |
encodeURIComponent 或框架內建序列化方法,切勿手動拼接 URL。