PHP 實例 - AJAX 實時搜索
AJAX 可為用戶提供更友好、交互性更強的搜索體驗。
AJAX Live Search
在下面的實例中,我們將演示一個實時的搜索,在您鍵入數據的同時即可得到搜索結果。
實時的搜索與傳統的搜索相比,具有很多優勢:
- 當鍵入數據時,就會顯示出匹配的結果
- 當繼續鍵入數據時,對結果進行過濾
- 如果結果太少,刪除字符就可以獲得更寬的范圍
在下面的文本框中搜索 W3CSchool 的頁面
上面實例中的結果在一個 XML 文件(links.xml)中進行查找。為了讓這個例子小而簡單,我們只提供 6 個結果。
實例解釋 - HTML 頁面
當用戶在上面的輸入框中鍵入字符時,會執行 "showResult()" 函數。該函數由 "onkeyup" 事件觸發:
<html>
<head>
<script>
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
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),該函數會清空 livesearch 占位符的內容,并退出該函數。
如果輸入框不是空的,那么 showResult() 會執行以下步驟:
- 創建 XMLHttpRequest 對象
- 創建在服務器響應就緒時執行的函數
- 向服務器上的文件發送請求
- 請注意添加到 URL 末端的參數(q)(包含輸入框的內容)
PHP 文件
上面這段通過 JavaScript 調用的服務器頁面是名為 "livesearch.php" 的 PHP 文件。
"livesearch.php" 中的源代碼會搜索 XML 文件中匹配搜索字符串的標題,并返回結果:
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
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)
{
//find a link matching the search text
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>";
}
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
如果 JavaScript 發送了任何文本(即 strlen($q) > 0),則會發生:
- 加載 XML 文件到新的 XML DOM 對象
- 遍歷所有的 <title> 元素,以便找到匹配 JavaScript 所傳文本
- 在 "$response" 變量中設置正確的 URL 和標題。如果找到多于一個匹配,所有的匹配都會添加到變量。
- 如果沒有找到匹配,則把 $response 變量設置為 "no suggestion"。