【发布时间】:2014-04-17 20:22:58
【问题描述】:
您好,我正在处理以下与下拉列表一样工作的代码,我希望将下拉列表替换为具有数据库数据自动完成功能的文本框。
问题在于,对于下拉列表,代码中已经有硬编码选项可供选择,与文本框一样,它应该根据数据库值生成每个选项。
我不知道该怎么做,任何帮助都会很棒:)
这是我现在的代码:
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);
?>
【问题讨论】:
-
您想要动态填充的下拉列表或带有自动完成功能的文本框,例如 jqueryui.com/autocomplete
-
@HüseyinBABAL 我希望它有一个文本框,当您在文本框中键入时,该文本框会自动填充来自 mySQL 的数据。
-
使用jquery自动补全可以吗?
-
@HüseyinBABAL 这完全没问题。