accept-charset 屬性HTML 標準屬性,指定表單提交時的字元編碼,**不受頁面本身編碼影響**。
<form action="https://legacy-system.example.com/search" method="GET" accept-charset="gb2312">
<input name="keyword" type="text">
<button type="submit">查詢</button>
</form>
onsubmit 設定 document.charsetIE 專屬非標準屬性,提交前臨時修改文檔編碼:
<form action="..." method="GET" accept-charset="gb2312"
onsubmit="document.charset='gb2312';">
<!-- 表單欄位 -->
</form>
<form id="searchForm" action="/legacy-search" method="GET" accept-charset="gb2312">
<input name="q" type="text" placeholder="輸入關鍵字">
<button type="submit">搜尋</button>
</form>
<script>
// IE 降級處理:提交前強制設定 document.charset
const form = document.getElementById("searchForm");
if (/*@cc_on!@*/false || !!document.documentMode) { // 簡易 IE 偵測
form.onsubmit = function() {
document.charset = "gb2312";
// 注意:IE 下 document.charset 設定後會影響後續頁面,
// 建議提交完成後恢復,但表單提交通常會跳轉/重載,故通常無需恢復。
};
}
</script>
accept-charset (或頁面編碼) 將字串**編碼為位元組序列**。Content-Type: charset=... 或預設編碼**解碼**為字串處理。accept-charset 如何修正?瀏覽器讀取該屬性,**改用指定編碼 (GB2312) 進行參數編碼**,位元組序列與伺服器預期一致,解碼正確。
若使用 `fetch`/`XMLHttpRequest` 提交,需手動編碼:
// 使用 TextEncoder (現代) + 手動組裝 application/x-www-form-urlencoded
async function submitLegacyForm(data) {
// 1. 將物件轉為鍵值對字串
const params = new URLSearchParams(data).toString(); // UTF-8 百分比編碼
// 2. 轉為 GB2310 位元組 (需引入 encoding.js 或 iconv-lite)
// 瀏覽器原生不支援 GB2312 編碼,需引入編碼庫
// import { encode } from 'iconv-lite'; // Node.js
// 瀏覽器端可用 encoding-japanese 或自建映射表 (不建議)
// 實務上:後端應升級支援 UTF-8,避免前端處理舊編碼
const response = await fetch("/legacy-api", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded; charset=gb2312" },
body: params // 瀏覽器會嘗試用 UTF-8 編碼 body,charset 宣告可能被忽略
});
}
> ⚠️ **重要**:瀏覽器端 **無原生 API 將字串編碼為 GB2312/Big5**。實務上若必須對接舊系統,**強烈建議後端升級支援 UTF-8**,或由後端提供 UTF-8 介面轉碼。前端硬編碼舊字集極易出錯且維護成本高。
<form accept-charset="gb2312"> + IE onsubmit hack。Content-Type: text/html; charset=gb2312 標頭,瀏覽器才能正確解碼回應頁面。accept-charset 是 HTML 標準解決表單跨編碼提交的正統之道,配合 IE 專屬 document.charset hack 可覆蓋 99% 使用者。但**根治之道在後端統一 UTF-8**,前端不應承擔字元編碼轉換的複雜度與風險。