AJAX 可為用戶提供更友好、交互性更強(qiáng)的搜索體驗(yàn)。


AJAX Live Search

在下面的實(shí)例中,我們將演示一個(gè)實(shí)時(shí)的搜索,在您鍵入數(shù)據(jù)的同時(shí)即可得到搜索結(jié)果。

實(shí)時(shí)的搜索與傳統(tǒng)的搜索相比,具有很多優(yōu)勢(shì):

  • 當(dāng)鍵入數(shù)據(jù)時(shí),就會(huì)顯示出匹配的結(jié)果

  • 當(dāng)繼續(xù)鍵入數(shù)據(jù)時(shí),對(duì)結(jié)果進(jìn)行過濾

  • 如果結(jié)果太少,刪除字符就可以獲得更寬的范圍

在下面的文本框中輸入 "HTML",搜索包含 HTML 的頁面:

上面實(shí)例中的結(jié)果在一個(gè) XML 文件(links.xml)中進(jìn)行查找。為了讓這個(gè)例子小而簡(jiǎn)單,我們只提供 6 個(gè)結(jié)果。


實(shí)例解釋 - HTML 頁面

當(dāng)用戶在上面的輸入框中鍵入字符時(shí),會(huì)執(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ù)會(huì)清空 livesearch 占位符的內(nèi)容,并退出該函數(shù)。

如果輸入框不是空的,那么 showResult() 會(huì)執(zhí)行以下步驟:

  • 創(chuàng)建 XMLHttpRequest 對(duì)象

  • 創(chuàng)建在服務(wù)器響應(yīng)就緒時(shí)執(zhí)行的函數(shù)

  • 向服務(wù)器上的文件發(fā)送請(qǐng)求

  • 請(qǐng)注意添加到 URL 末端的參數(shù)(q)(包含輸入框的內(nèi)容)


PHP 文件

上面這段通過 JavaScript 調(diào)用的服務(wù)器頁面是名為 "livesearch.php" 的 PHP 文件。

"livesearch.php" 中的源代碼會(huì)搜索 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),則會(huì)發(fā)生:

  • 加載 XML 文件到新的 XML DOM 對(duì)象

  • 遍歷所有的 <title> 元素,以便找到匹配 JavaScript 所傳文本

  • 在 "$response" 變量中設(shè)置正確的 URL 和標(biāo)題。如果找到多于一個(gè)匹配,所有的匹配都會(huì)添加到變量。

  • 如果沒有找到匹配,則把 $response 變量設(shè)置為 "no suggestion"。

相關(guān)視頻教程推薦:《AJAX教程http://miracleart.cn/course/list/25.html