我试图提出像谷歌这样的搜索建议......
我创建了一个表标签和一个单列标签,其中存储了一些标签,但问题是当我没有输入任何内容或数据库中的内容时,我得到未定义为返回
但是当我输入一些不在数据库中的东西时,我很抱歉[这是正确的]
我正在使用 Ajax
我的PHP代码
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$searchvalue=$_GET['searchvalue'];
$con=mysqli_connect("localhost","root","","myweb") or die("error connecting db");
$sqlresult = mysqli_query($con,"SELECT tag FROM tags where tag like '".$searchvalue."%'");
$suggests="";
while($row = mysqli_fetch_array($sqlresult))
{
$suggests=$suggests.$row.',';
}
//$suggarray=explode(",",$suggests);
if(strlen($suggests)>0)
{
echo "found";
}
else
{
echo "sorry! for ".$searchvalue;
}
mysqli_close($con);
echo '</response>';
?>
用于 ajax 的 JavaScript
// JavaScript for search ajax
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
//alert("create obj");
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp =false;
}
}else{
try{
xmlHttp= new XMLHttpRequest();
}catch(e){
xmlHttp =false;
}
}
if(!xmlHttp)
alert("cant create that object hoss!");
else
return xmlHttp;
}
function searchprocess(){
//alert("start");
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
searchtext=encodeURIComponent(document.getElementById("searchvalue").value );
xmlHttp.open("GET", "pages/search_suggestions.php?searchvalue="+searchtext, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('searchprocess()', 1000);
}
}
function handleServerResponse(){
//alert("handle");
if(xmlHttp.readyState==4){
//alert("handle ready");
if(xmlHttp.status==200 || xmlHttp.status==304){
//alert("inside");
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("tempo").innerHTML=message;
setTimeout('searchprocess()', 1000);
}else{
alert("Something went wrong!");
}
}
}
// end of JavaScript for search ajax