AJAX 可為用戶提供更友好、交互性更強的搜索體驗。
AJAX Live Search
在下面的實例中,我們將演示一個實時的搜索,在您鍵入數(shù)據(jù)的同時即可得到搜索結(jié)果。
實時的搜索與傳統(tǒng)的搜索相比,具有很多優(yōu)勢:
當鍵入數(shù)據(jù)時,就會顯示出匹配的結(jié)果
當繼續(xù)鍵入數(shù)據(jù)時,對結(jié)果進行過濾
如果結(jié)果太少,刪除字符就可以獲得更寬的范圍
在下面的文本框中輸入 "HTML",搜索包含 HTML 的頁面:
上面實例中的結(jié)果在一個 XML 文件(links.xml)中進行查找。為了讓這個例子小而簡單,我們只提供 6 個結(jié)果。
實例解釋 - HTML 頁面
當用戶在上面的輸入框中鍵入字符時,會執(zhí)行 "showResult()" 函數(shù)。該函數(shù)由 "onkeyup" 事件觸發(fā):
<html> <head> <script> function showResult(str) { if (str.length==0) { document.getElementById("livesearch").innerHTML=""; document.getElementById("livesearch").style.border="0px"; return; } if (window.XMLHttpRequest) {// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行 xmlhttp=new XMLHttpRequest(); } else {// IE6, IE5 瀏覽器執(zhí)行 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch").innerHTML=xmlhttp.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","livesearch.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <input type="text" size="30" onkeyup="showResult(this.value)"> <div id="livesearch"></div> </form> </body> </html>
源代碼解釋:
如果輸入框是空的(str.length==0),該函數(shù)會清空 livesearch 占位符的內(nèi)容,并退出該函數(shù)。
如果輸入框不是空的,那么 showResult() 會執(zhí)行以下步驟:
創(chuàng)建 XMLHttpRequest 對象
創(chuàng)建在服務(wù)器響應(yīng)就緒時執(zhí)行的函數(shù)
向服務(wù)器上的文件發(fā)送請求
請注意添加到 URL 末端的參數(shù)(q)(包含輸入框的內(nèi)容)
PHP 文件
上面這段通過 JavaScript 調(diào)用的服務(wù)器頁面是名為 "livesearch.php" 的 PHP 文件。
"livesearch.php" 中的源代碼會搜索 XML 文件中匹配搜索字符串的標題,并返回結(jié)果:
<?php $xmlDoc=new DOMDocument(); $xmlDoc->load("links.xml"); $x=$xmlDoc->getElementsByTagName('link'); // 從 URL 中獲取參數(shù) q 的值 $q=$_GET["q"]; // 如果 q 參數(shù)存在則從 xml 文件中查找數(shù)據(jù) if (strlen($q)>0) { $hint=""; for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { // 找到匹配搜索的鏈接 if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } else { $hint=$hint . "<br /><a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes->item(0)->nodeValue . "</a>"; } } } } } // 如果沒找到則返回 "no suggestion" if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } // 輸出結(jié)果 echo $response; ?>
如果 JavaScript 發(fā)送了任何文本(即 strlen($q) > 0),則會發(fā)生:
加載 XML 文件到新的 XML DOM 對象
遍歷所有的 <title> 元素,以便找到匹配 JavaScript 所傳文本
在 "$response" 變量中設(shè)置正確的 URL 和標題。如果找到多于一個匹配,所有的匹配都會添加到變量。
如果沒有找到匹配,則把 $response 變量設(shè)置為 "no suggestion"。
相關(guān)視頻教程推薦:《AJAX教程》http://miracleart.cn/course/list/25.html