使用 $.post 發送資料時,若 payload 包含 <、> 等特殊字元,可能導致請求靜默失敗、伺服器解析錯誤或 WAF 攔截。本文分析根因、提供轉義工具函數,並說明現代 fetch / axios 的正確處理方式。
var jsonStr = '{"value":"abcd
$.param() 會對資料做 application/x-www-form-urlencoded 編碼< > & = 等在 URL 編碼中有特殊含義$_POST、Java request.getParameter() 依賴標準編碼<script> 等模式觸發 XSS 防護function escapeHtmlChars(str) {
return String(str)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 使用
var jsonStr = '{"value":"abcd
⚠️ 注意:這只是將字元實體化,伺服器端需對應解碼 (PHP html_entity_decode),否則資料庫存入 < 而非 <。
不要手動拼 JSON 字串,直接傳遞物件,讓 $.param() 正確編碼:
// ✅ 正確:傳遞物件,jQuery 自動序列化並編碼
$.post('/api/save', {
value: 'abcdspecial' }
}, callback);
// ✅ 若必須傳 JSON 字串:先建物件,再 JSON.stringify
const payload = { value: 'abcdspecial' } };
$.post('/api/save', { jsonstr: JSON.stringify(payload) }, callback);
// jQuery 會正確編碼 { } " : < > 等字元為 %7B %7D %22 %3A %3C %3E
async function postJson(url, data) {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data) // 正確序列化,無編碼問題
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// 使用
postJson('/api/save', { value: 'abcdspecial' } })
.then(data => console.log('成功:', data))
.catch(err => console.error('失敗:', err));
import axios from 'axios';
axios.post('/api/save', { value: 'abcd
| 字元 | URL 編碼 | HTML 實體 | JSON 轉義 |
|---|---|---|---|
< | %3C | < | \u003C 或 直接保留 (JSON 字串中合法) |
> | %3E | > | \u003E |
& | %26 | & | \u0026 |
" | %22 | " | \" |
' | %27 | ' | 字串界定符需轉義 |
| 平台 | Content-Type | 解析方式 |
|---|---|---|
| PHP | application/x-www-form-urlencoded | $_POST 自動解碼 |
| PHP | application/json | json_decode(file_get_contents('php://input'), true) |
| Node/Express | application/json | express.json() middleware → req.body |
| Java/Spring | application/json | @RequestBody DTO |
| Python/Flask | application/json | request.get_json() |
JSON.stringify(obj) 產生fetch/axios,Content-Type: application/json 避免編碼地獄Content-Type 正確解析編碼問題 90% 來自「手工拼字串」。用對工具、傳對格式,問題自然消失。