从mysql数据库自动在textfield中完成多个结果

时间:2014-08-29 08:42:44

标签: php mysql ajax

我是php和ajax的新手。我已经从互联网上搜索了很多这个问题,但是徒劳无功。我想像这个网站一样建立一个自动完成系统:(http://www.zameen.com/)。我的问题比这个网站更简单。我的要求是:"当我在文本字段中输入内容时,它将显示数据库的匹配结果。当我选择其中一个结果时,它将显示在同一文本字段中。我想选择多个结果,所有结果都会显示在同一个文本字段中。"

现在我的下一个问题是:"我将如何在php变量中处理所有这些结果并将它们发布到我所需的文件中。"

我很困惑。请给出一个简单的解决方案,因为我是php和ajax的新手。

您可以在此链接上看到图片以了解我的问题:(http://mutaliapakistan.com/problem.png)。

1 个答案:

答案 0 :(得分:0)

我会尝试为您提供一个简单,实用的例子:

这将是你的livesearch.js文件:

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 (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();
}

这将是你的livesearch.php文件:

<?php
$hint="";
//get the q parameter from URL
if (!isset($key))$key = $_GET['q'];
//include the mysql conn script
require_once ('mysql_connect.php');

//just change the selects here to what you want/ need.
$query = "SELECT DISTINCT * FROM table_name WHERE display='1' AND (name LIKE '%$key%' OR description LIKE '%$key%') LIMIT 5";
$result = mysql_query($query); 
while($result_row = mysql_fetch_array($result))
{
$found = $result_row[12];
if (strlen($found)>25)
{
$found = substr($found, 0, 25) . '...';
}
$hint = $hint."<div id='search_result'><a href=\"http://example.com/index.php?category=$result_row[3]&name=$result_row[1]&id=$result_row[0]\">".$found."</a></div>";
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
  {
  $response = "No results";
  }
else
  {
  $response = $hint;
  }
//output the response
echo $response;
?>

现在终于到了你要在其中搜索seach的页面添加以下内容:

<script type="text/javascript" src="livesearch.js"></script>
<div class="search">
<form name="frm_search" id="frm_search" method="get" action="advanced_search.php">
<input type="text" name="search" id="search" value="" placeholder="&nbsp;&nbsp;Search" onkeyup="showResult(this.value)"/>
<input type="submit" name="search_go" id="search_go" value="↵"/>
</form>
<div id="livesearch" style="margin-left:3px;background-color:#fff;text-align:left;">
</div>
</div>

我希望它清楚。