章 37. 處理 XForms

XForms 定義了一種傳統 web 表單的變種,它可以用於更多的平台和瀏覽器,甚至非傳統的媒體例如 PDF 文件。

XFroms 的第一個關鍵區別是表單怎樣傳送到用戶端。XForms for HTML Authors 包括有怎樣建立 XForms 的詳細說明。本節只看一個簡單例子。

例子 37-1. 一個簡單的 XForms 搜尋表單

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" 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>

上面的表單顯示一個文字輸入框(命名為 q)和一個送出按鈕。當點閱送出按鈕,表單將被傳送到 action 所指示的頁面。

下面是從 web 套用端的角度看上去的區別。在普通的 HTML 表單中,資料傳送格式是 application/x-www-form-urlencoded,在 XForms 的世界中,該訊息是以 XML 格式資料傳送的。

若果選取使用 XForms,那麼資料為 XML,這種情況下,在 $HTTP_RAW_POST_DATA 中包括了由瀏覽器產生的 XML 文件,可以將其傳遞給所偏好的 XSLT 引擎或是文件解析器。

若果對格式不感興趣,只想讓資料進入到傳統的 $_POST 變量中,可以指示用戶端瀏覽器將其以 application/x-www-form-urlencoded 格式傳送,只要將 method 屬性改成 urlencoded-post 即可。

例子 37-2. 使用 XForm 來產生 $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" 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>

注: 在寫本文件時,許多瀏覽器還不支援 XForms。若果上面例子失敗請檢查自己的瀏覽器版本。