使用最少字符的PHP AJAX XML实时搜索



我的问题与您可以在W3Schools上找到的Ajax PHP Live搜索有关。我只想得到超过2个字符的结果,但我似乎不知道在哪里更改它……我也研究了一段时间,但没有发现任何关于这个与最小字符有关的特定代码的信息。。。

我尝试过将str.length==0更改为1和/或if(strlen($q(>0(更改为1,这在一开始起作用,并在键入至少2个字符后给出结果,但当在搜索字段中使用退格到0个字符时,它会返回一个错误,即变量"hint is undefined">

有什么建议吗?谢谢

这是代码:

<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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>  

和php:

<?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 was found
// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}
//output the response
echo $response;
?> 

当在搜索字段中使用退格到0个字符时,它会返回一个错误,即变量"hint is undefined">

因为变量hint是在if-else块中声明的。

if (strlen($q)>0) {
$hint="";

将变量移到外部:

$hint="";
if (strlen($q)>0) {

最新更新