把一段腳本文字透過 AJAX 送到後端,結果伺服器收到的內容裡原本的 + 全變成了空格——這是一個非常典型的編碼陷阱,足以讓原本正常的程式邏輯徹底走樣。
XML 裡嵌了一段 JavaScript 敘述:
<action xsi:type="basic:JavaScript" script="index += 1;"/>
var postData = "input=" + escape(inputJSON) + "&script=" + escape(xml)
+ "&feedGeneral=" + escape(feedGeneral);
XmlHttpRequest.open("POST", url, true);
XmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XmlHttpRequest.send(postData);
問題就在這裡:escape() 並不會編碼 + 這個字元。而當 Content-Type 宣告為 application/x-www-form-urlencoded 時,伺服器會依規範把 + 還原成空格。於是 index += 1; 到了後端就變成 index = 1;,等於把「累加」寫成了「指派」,Java 端執行這段腳本時自然陷入迴圈。
依 HTML 4.01 表單處理的說明,application/x-www-form-urlencoded 的編碼規則是:控制名稱與值都必須被轉義,空格會被替換成 +,接著其他保留字元才依 RFC1738 第 2.2 節處理——非英數字元換成 %HH(百分比符號加兩個十六進位數字),換行則表示為 %0D%0A。
換句話說,+ 在這個協定裡天生就帶有「空格」的語意,這不是瀏覽器的 bug,而是雙方對協定的理解不一致。
有趣的是,改成動態組出一個 form 再 submit(),同樣的 Content-Type 卻不會出問題:
$('test').innerHTML = "<form target='_blank' id='test_form' action='./gen_feed' method='post'>"
+ "<input type='text' name='input' /><input type='text' name='script' />"
+ "<input type='text' name='feedGeneral' />"
+ "<input type='hidden' name='format' value='" + this.feed_type + "' />"
+ "<input type='submit' value='gen' /></form>";
var test_form = $('test_form');
test_form.elements[0].value = inputJSON;
test_form.elements[1].value = script;
test_form.elements[2].value = feedGeneral;
test_form.submit();
差別在於瀏覽器在組裝表單本文時,會完整且正確地做一次 urlencode,把 + 也一併編碼為 %2B;而手工拼接字串時,escape() 的規則太舊、覆蓋範圍不足,才會漏掉這個字元。
把 escape() 換成 encodeURIComponent(),它會把 + 編碼成 %2B,後端解出來就還是加號:
var postData = "input=" + encodeURIComponent(inputJSON)
+ "&script=" + encodeURIComponent(xml)
+ "&feedGeneral=" + encodeURIComponent(feedGeneral);
如果資料是物件,更乾淨的方式是直接序列化成 JSON,並把 Content-Type 改為 application/json;charset=UTF-8,就完全不需要煩惱表單編碼的歷史包袱。
在還沒找出根因的那段時間,作者暫時把 script 裡的 + 全部換成 -,也就是把 index += 1; 改寫成 index -= -1;。看起來很詭異,卻的確能讓程式跑起來——這也提醒我們:遇到「資料莫名被改寫」的徵兆時,先去檢查編碼層,而不是急著改業務邏輯。