XForms/搜尋表單
您想要建立一個搜尋表單,該表單使用單個輸入文字欄位並將搜尋請求提交到遠端 Web 伺服器上的搜尋服務。
我們都熟悉 Google 等搜尋引擎的簡單前端,它們顯示一個簡單的搜尋欄位。在第一個版本中,我們將演示兩個簡單的功能。1) 當表單載入時,輸入游標將被定位在搜尋欄位中。當您按下“Enter”鍵時,搜尋將自動執行。
我們還將討論一種方法,讓單個表單同時顯示簡單搜尋和複雜搜尋功能。
我們將首先建立一個簡單的搜尋輸入欄位,併為其賦予“search-field”的 id。我們還將在輸入中新增一個操作,當按下 Enter 鍵時,該操作將觸發提交。
<xf:input ref="q" id="search-field">
<xf:label>Search string:</xf:label>
<xf:action ev:event="DOMActivate">
<xf:send submission="search"/>
</xf:action>
</xf:input>
在此示例中,q 是對我們將傳送到遠端伺服器的查詢字串的引用。
從前面的示例中我們瞭解到,您可以透過將以下操作新增到您的模型中,讓游標在表單載入時自動定位在搜尋欄位中
<xf:model>
...
<xf:action ev:event="xforms-ready">
<xf:setfocus control="search-field"/>
</xf:action>
...
</xf:model>

在此示例中,我們將建立一個 Google 搜尋引擎的簡單前端。Google 搜尋引擎的 REST API 格式如下
http://www.google.com/search?hl=en&q=XForms
在此 REST 查詢中,引數為
- hl = 語言(en 代表英語)
- q = 搜尋查詢字串
我們可以在我們的模型中建立一個具有這些引數的例項
<xf:instance xmlns="">
<data>
<hl>en</hl>
<q></q>
</data>
</xf:instance>
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xf="http://www.w3.org/2002/xforms"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:ev="http://www.w3.org/2001/xml-events" >
<head>
<title>Google Search Example</title>
<style type="text/css">
body {font-family: Helvetica, sans-serif}
</style>
<xf:model>
<xf:instance xmlns="" id ="search-params">
<data>
<hl>en</hl>
<q></q>
</data>
</xf:instance>
<!-- Send the search parameters to the Google search engine and replace this entire form with the results -->
<xf:submission id="search-google" method="get"
action="http://www.google.com/search" replace="all"
separator="&"/>
<!-- put the cursor in the first field when the form becomes ready -->
<xf:action ev:event="xforms-ready">
<xf:setfocus control="search-field"/>
</xf:action>
</xf:model>
</head>
<body>
<h1>Google Search Example</h1>
<xf:input ref="instance('search-params')/q" id="search-field">
<xf:label>Search string:</xf:label>
<xf:action ev:event="DOMActivate">
<xf:send submission="search-google"/>
</xf:action>
</xf:input>
<xf:submit submission="search-google">
<xf:label>Search</xf:label>
</xf:submit>
</body>
</html>
您還可以將十幾個其他引數傳送到 Google 搜尋服務。例如,如果您想將搜尋結果限制到特定的網站或子網站,您只需新增一個額外的“site”引數,將搜尋結果限制到該網站。例如,以下 URL 將將搜尋結果限制到此華夏公益教科書中的頁面
http://www.google.com/search?hl=en&q=xforms+site%3Ahttp%3A%2F%2Fen.wikibooks.org%2Fwiki%2FXForms
請注意,由於正斜槓是搜尋查詢的一部分,因此它們被替換為%2F字串。
您可能還會對 OpenSearch XML 標準感興趣。此標準允許任何搜尋服務指定搜尋引擎的引數以及如何將資料返回給搜尋客戶端。