XForms 與傳統表單最關鍵的差異之一,是「表單如何送到伺服器端」。關於 XForms 標籤怎麼寫,可參考 XForms for HTML Authors 的詳細說明;這裡只用一個簡單範例把重點帶過。
<h:html XMLns:h="https://www.w3.org/1999/xHtml" XMLns="https://www.w3.org/2002/xforms"> <h:head> <h:title>Search</h:title> <model> <submission action="https://example.com/search" method="post" XML:id="s"/> </model> </h:head> <h:body> <h:p> <input ref="q"><label>Find</label></input> <submit submission="s"><label>Go</label></submit> </h:p> </h:body> </h:Html>
畫面上就是一個文字輸入框(ref 為 q)和一顆提交按鈕。按下按鈕後,表單會送到 submission 的 action 所指定的位址。
從 Web 應用程式的角度看,差異出在資料格式:傳統 HTML 表單送的是 application/x-www-form-urlencoded,而 XForms 送的是一段 XML。
如果採用 XForms 的預設行為,伺服器端會在 $HTTP_RAW_POST_DATA 中拿到瀏覽器產生的 XML 文件,接著就能把它交給偏好的 XSLT 引擎或 XML 解析器處理。
若你不在意格式,只希望資料照舊進到 $_POST,也有現成做法:把 method 屬性改成 urlencoded-post,瀏覽器就會用 traditional 的表單編碼送出。
<h:html XMLns:h="https://www.w3.org/1999/xHtml" XMLns="https://www.w3.org/2002/xforms"> <h:head> <h:title>Search</h:title> <model> <submission action="https://example.com/search" method="urlencoded-post" XML:id="s"/> </model> </h:head> <h:body> <h:p> <input ref="q"><label>Find</label></input> <submit submission="s"><label>Go</label></submit> </h:p> </h:body> </h:Html>
整份文件與範例一幾乎相同,唯一的改動就是 submission 的 method。對既有以 $_POST 為基礎的後端而言,這是遷移成本最低的一條路。
提醒:本文撰寫時,多數瀏覽器尚未原生支援 XForms。若上述範例沒有作用,請先確認瀏覽器版本與是否已安裝對應的 XForms 擴充功能。