扩展我的AJAX数据库查询的功能

时间:2014-04-17 08:16:49

标签: php html mysql ajax

您好我正在处理下面的代码,它正在使用下拉列表,我希望将下拉列表替换为具有自动完成功能的文本框以及数据库中的数据。

问题是,使用下拉列表时,代码中已经有硬编码选项可供选择,文本框应根据数据库值生成每个选项。

我坚持如何做到这一点,任何帮助都会很棒:)

这是我目前的代码:

HTML:

<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html> 

PHP

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','root','l3tm31n','records');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"records");
$sql="SELECT * FROM workers WHERE id = '".$q."'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
<th>hasCar</th>
<th>speaksForeignLanguage</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['hasCar'] . "</td>";
echo "<td>" . $row['speaksForeignLanguage'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?> 

2 个答案:

答案 0 :(得分:0)

将您的mysql查询更改为

SELECT * FROM workers WHERE name LIKE'%$ q%'

答案 1 :(得分:0)

你可以用jquery autocomplete

来做到这一点

首先,您需要包含jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

和jquery ui

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

然后创建文本框;

<input type="text" name="names" value=""/>

制作自动填充处理程序,

<?php 
$q = $_GET["q"];

// Do your db connections

$sql = "SELECT * FROM workers WHERE name = '%" . $q . "'%";

$result = mysqli_query($con,$sql);

$users = array();

while($row = mysqli_fetch_array($result))
{
    $users[] = $row;
}

mysqli_close($con);

echo json_encode($users);


?> 

在你的js;

$( "#names" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      type:"get",
      url: "getuser.php?q=" + request.term,
      success: function( data ) {
        response( $.map( data, function( user ) {
          return {
            label: user.name,
            value: user.id
          }
        }));
      }
    });
  },
  minLength: 1,
  select: function( event, ui ) {
    log( ui.item ?
      "Selected: " + ui.item.label :
      "Nothing selected, input was " + this.value);

    $.ajax({
        "url": "getuser.php?q=" + ui.item.id,
        "type": "get",
        success: function(response) {
            $("#txtHint").html(response);
        }
    });
  },
  open: function() {
    $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
});