查詢是網站上最常見的功能模組之一。傳統架構下,每一次查詢都要打一次後端資料庫;但實際上使用者往往只針對一小塊資料操作,於是伺服器白扛負擔,使用者還得乾等。
更合理的做法是:把使用者需要的那批資料以 XML 形式一次送到用戶端,後續的篩選都在本機完成。既改善了互動速度,也替資料庫卸下重擔,而且這個模式可以複用到許多其他模組上。
兩個檔案:search.XML(資料)與 search.xsl(格式)。
<?XML version="1.0" encoding="gb2312" ?>
<?XML-stylesheet type="text/xsl" href="search.xsl" ?>
<BlueIdea>
<team>
<blue_ID>1</blue_ID>
<blue_name>Sailflying</blue_name>
<blue_text>一個簡單的查詢</blue_text>
<blue_time>2002-1-11 17:35:33</blue_time>
<blue_class>XML專題</blue_class>
</team>
…(共 5 筆 team 資料)
</BlueIdea>
<script>
function searchtext(x)
{
stylesheet = document.XSLDocument;
source = document.XMLDocument;
sortFIEld = document.XSLDocument.selectNodes("//@select");
if (x != "")
{
sortFIEld[1].value = "team[blue_ID='"+x+"']";
Layer1.innerHtml = source.documentElement.transformNode(stylesheet);
}
else { alert("請輸入篩選條件!"); }
}
</script>
輸入區與結果區的 HTML:
<div id="Layer1" name="Layer1">
<xsl:apply-templates select="BlueIdea" />
</div>
<hr size="1" width="500" />
<table align="center" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<span>請輸入篩選條件 : </span>
blue_ID= <input type="text" name="searchtext" size="1" maxlength="1" />
<input type="button" class="button" onClick="searchtext(document.all.searchtext.value)" value="Search" name="button" />
</td>
</tr>
</table>
樣式表裡的資料列模板則保持單純,逐欄輸出各子節點:
<xsl:template match="team">
<tr align="center">
<xsl:apply-templates select="blue_ID" />
<xsl:apply-templates select="blue_name" />
<xsl:apply-templates select="blue_text" />
<xsl:apply-templates select="blue_time" />
<xsl:apply-templates select="blue_class" />
</tr>
</xsl:template>
sortFIEld = document.XSLDocument.selectNodes("//@select");
找出所有帶有 select 屬性的節點。這裡和動態排序那篇用的 selectSingleNode("//@order-by") 有個小小但關鍵的差異:這次用 selectNodes 取回的是集合,因此後續以索引 [1] 指定第二個節點,也就是樣式表中這一行:
<xsl:apply-templates select="team" order-by="blue_ID"/>
sortFIEld[1].value = "team[blue_ID='"+x+"']";
參數 x 是文字方塊輸入的值。這行程式等於把原本的 select="team" 改寫成 select="team[blue_ID='x']",也就是加上一個條件:只有 blue_ID 等於 x 的節點才會被輸出。最後再重新指定 Layer1 的 innerHtml,畫面就換成篩選後的結果。
我在範例裡只做了單一條件的判斷,方便理解;實際上條件可以任意擴充,例如多欄位組合、模糊比對等。
索引位置要算準。這裡 select="team" 剛好是 sortFIEld[1],但你自己的樣式表結構若不同,位置就會改變,找錯節點是常見的除錯來源。實務上可以在程式裡用迴圈逐一判斷節點,找出真正需要的那一個,比硬編索引安全得多。
XML 對大小寫極為嚴格。標籤名、屬性名寫得不規範,解析器不會通融,直接就報錯。
做完動態排序與動態查詢之後你會發現,兩者的實作骨架其實是同一套:改一個值,然後重新顯示。接下來的動態分頁,走的仍然是這條路。