PHP 實例 - AJAX 即時搜尋
PHP 實例 -?AJAX 即時搜尋
AJAX 可為使用者提供更友善、互動性更強(qiáng)的搜尋體驗。
AJAX Live Search
在下面的實例中,我們將示範(fàn)一個即時的搜索,在您鍵入資料的同時即可得到搜尋結(jié)果。
即時的搜尋與傳統(tǒng)的搜尋相比,具有許多優(yōu)勢:
當(dāng)鍵入資料時,就會顯示出符合的結(jié)果
當(dāng)繼續(xù)鍵入資料時,對結(jié)果進(jìn)行過濾
如果結(jié)果太少,刪除字元就可以獲得更寬的範(fàn)圍
在下面的文字方塊中輸入"HTML",搜尋包含HTML 的頁面:
上面實例中的結(jié)果在一個XML 檔案(links.xml)中進(jìn)行尋找。為了讓這個例子小而簡單,我們只提供 6 個結(jié)果。
實例解釋 - HTML 頁面
當(dāng)使用者在上面的輸入框中鍵入字元時,會執(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í)行以下步驟:
#建立XMLHttpRequest 物件
建立在伺服器回應(yīng)就緒時執(zhí)行的函數(shù)
向伺服器上的檔案傳送請求
請注意新增到URL 末端的參數(shù)(q)(包含輸入方塊的內(nèi)容)
PHP 檔案
上面這段透過JavaScript 呼叫的伺服器頁面是名為"livesearch.php" 的PHP 檔案。
"livesearch.php" 中的原始程式碼會搜尋XML 檔案中符合搜尋字串的標(biāo)題,並傳回結(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ù)中設(shè)定正確的URL 和標(biāo)題。如果找到多於一個匹配,所有的匹配都會加到變數(shù)。
如果沒有找到匹配,則把 $response 變數(shù)設(shè)為 "no suggestion"。