AJAX Live Search仅在以相同的第一个字母开头时显示结果

时间:2013-11-08 02:55:02

标签: javascript php jquery ajax

我有一个使用这个w3school示例制作的ajax实时搜索栏。 http://www.w3schools.com/php/php_ajax_livesearch.asp

我如何才能让它只显示以第一个字母开头的相同顺序的字母结果,而不是匹配单词中任何一大块字母。例如,要显示“COMPUTER”,您必须键入“COM ...”而不是“PUTER”。

我相信我已经把它缩小到了这里的某个地方:

//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 . "<a href='" . 
        $z->item(0)->childNodes->item(0)->nodeValue . 
        "' target='_blank'>" . 
        $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

检查搜索项目的条件语法:

//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))

这是在项目的任何部分进行搜索$q,您要做的只是搜索它是否以$q开头,因此您必须更改语法:

if (strpos(strtolower($y->item(0)->childNodes->item(0)->nodeValue), strtolower($q)) === 0)

所以现在它将搜索开头的匹配(位置=== 0)。您还注意到我在两个比较值中都使用strtolower(),这是因为strpos()区分大小写,而stristr()则不区分。

您现在可以尝试更改此行并告诉我们它是否有效吗?

相关问题