處理 XForms

? XForms 定義了一種傳統(tǒng) web 表單的變種,它可以用于更多的平臺和瀏覽器,甚至非傳統(tǒng)的媒體例如 PDF 文檔。

XFroms 的第一個關(guān)鍵區(qū)別是表單怎樣發(fā)送到客戶端。? XForms for HTML Authors 包含有怎樣創(chuàng)建 XForms 的詳細(xì)說明。本節(jié)只看一個簡單例子。

示例 #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" 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>

上面的表單顯示一個文本輸入框(命名為 q)和一個提交按鈕。當(dāng)點(diǎn)擊提交按鈕,表單將被發(fā)送到 action 所指示的頁面。

下面是從 web 應(yīng)用端的角度看上去的區(qū)別。在普通的 HTML 表單中,數(shù)據(jù)發(fā)送格式是 application/x-www-form-urlencoded,在 XForms 的世界中,該信息是以 XML 格式數(shù)據(jù)發(fā)送的。

如果選擇使用 XForms,那么數(shù)據(jù)為 XML,這種情況下,在 $HTTP_RAW_POST_DATA 中包含了由瀏覽器產(chǎn)生的 XML 文檔,可以將其傳遞給所偏好的 XSLT 引擎或者文檔解析器。

如果對格式不感興趣,只想讓數(shù)據(jù)進(jìn)入到傳統(tǒng)的 $_POST 變量中,可以指示客戶端瀏覽器將其以 application/x-www-form-urlencoded 格式發(fā)送,只要將 method 屬性改成 urlencoded-post 即可。

示例 #2 使用 XForm 來產(chǎn)生 $_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" 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>

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