傳統 HTML 表單以 key-value pairs 送到伺服器,這種格式對結構化資料的表達力相當有限。以 JSON 格式提交表單是 HTML5 帶來的改進:瀏覽器會把表單內容打包成有規範的 JSON 結構,伺服器端收到的就是可直接使用的 JSON。
大家應該很熟悉上傳檔案要在 form 上寫 enctype="multipart/form-data"。JSON 提交表單的寫法與此類似:
<form enctype='application/json'> ... </form>
這是 HTML5 中相當新的規範,只有實作它的現代瀏覽器才認得 application/json 的語義。舊瀏覽器無法識別時,enctype 會自動退化成預設的 application/x-www-form-urlencoded。因此伺服器端可以依 enctype 的值判斷要用哪種方式解析,做出平滑降級。
<form enctype='application/json'>
<input name='name' value='Bender'>
<select name='hind'>
<option selected>Bitable</option>
<option>Kickable</option>
</select>
<input type='checkbox' name='shiny' checked>
</form>
// 產生的 JSON:
{ "name": "Bender", "hind": "Bitable", "shiny": true }
<form enctype='application/json'>
<input type='number' name='bottle-on-wall' value='1'>
<input type='number' name='bottle-on-wall' value='2'>
<input type='number' name='bottle-on-wall' value='3'>
</form>
// 產生的 JSON:
{ "bottle-on-wall": [1, 2, 3] }
<form enctype='application/json'>
<input name='pet[species]' value='Dahut'>
<input name='pet[name]' value='Hypatia'>
<input name='kids[1]' value='Thelma'>
<input name='kids[0]' value='Ashley'>
</form>
// 產生的 JSON:
{ "pet": { "species": "Dahut", "name": "Hypatia" },
"kids": ["Ashley", "Thelma"] }
<form enctype='application/json'>
<input name='hearbeat[0]' value='thunk'>
<input name='hearbeat[2]' value='thunk'>
</form>
// 產生的 JSON:
{ "hearbeat": ["thunk", null, "thunk"] }
<form enctype='application/json'>
<input name='pet[0][species]' value='Dahut'>
<input name='pet[0][name]' value='Hypatia'>
<input name='pet[1][species]' value='Felis Stultus'>
<input name='pet[1][name]' value='Billie'>
</form>
// 產生的 JSON:
{ "pet": [
{ "species": "Dahut", "name": "Hypatia" },
{ "species": "Felis Stultus", "name": "Billie" } ] }
<form enctype='application/json'>
<input name='wow[such][deep][3][much][power][!]' value='Amaze'>
</form>
// 產生的 JSON:
{ "wow": { "such": { "deep": [
null, null, null,
{ "much": { "power": { "!": "Amaze" } } } ] } } }
<form enctype='application/json'>
<input type='file' name='file' multiple>
</form>
// 假設上傳了 2 個檔案,產生的 JSON:
{ "file": [
{ "type": "text/plain", "name": "dahut.txt",
"body": "REFBQUFBQUFIVVVVVVVVVVVVVCEhIQo=" },
{ "type": "text/plain", "name": "litany.txt",
"body": "SSBtdXN0IG5vdCBmZWFyLlxuRmVhciBpcyB0aGUgbWluZC1raWxsZXIuCg==" } ] }
從這些範例可以看出設計上的巧思:name 屬性直接變成 JSON 的鍵路徑,pet[species] 形成物件、kids[0] 形成陣列、缺少的索引自動補 null、檔案內容以 Base64 編碼放進 body。表單從此不再只是扁平的 key-value,而是能自然表達巢狀結構的資料容器。