限制XML文件中回显的Ajax回复量

问题描述 投票:0回答:1

我正在创建一个AJAX-XML-PHP搜索引擎,并在w3schools上发现了一篇精彩的文章:here,但是我的XML文件非常庞大,并且只要键入一个或两个字母,它就会使页面向下滚动超长。我想要发生的是,如果你理解我的意思,那么php文件只能回复6个'可能的搜索'。这是我的代码:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("places.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL
$q=$_GET["q"];

$counter;

//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'); //$y = title
    $z=$x->item($i)->getElementsByTagName('url');   //$z = 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 was found
// or to the correct values
if ($hint=="") {
  $response="Hmm, nothing here!";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>

这是我的XML文件的片段:

<?xml version="1.0" encoding="UTF-8"?><places><link><title>Afghanistan</title><url>/places/Afghanistan</url></link><link><title>Albania</title><url>/places/Albania</url></link>

当然以</places>结尾。

我已经在这项任务中苦苦挣扎了大约2天,任何支持都会有所帮助!

注意:Ajax工作正常,客户端html + js也是如此,它只得到6个我不能做的回复!

javascript php ajax xml search
1个回答
2
投票

计算一下“好”的项目然后再检查一下

$minimumQLength = 4;
if (strlen($q)>$minimumQLength) {
    for($i=0; $i<($x->length); $i++) {
      if($hintcount<6){
        $y=$x->item($i)->getElementsByTagName('title'); //$y = title
         $z=$x->item($i)->getElementsByTagName('url');   //$z = url
          if ($y->item(0)->nodeType==1) {
             //find a link matching the search text
             if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
                $hintcount++;
                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>";
                }
             }
          }
     }
     else{
        break;
     }
   }
}

编辑:添加$ minimumQLength变量 - 使用它来要求更长的查询。

© www.soinside.com 2019 - 2024. All rights reserved.