我在一周内就被这个问题困扰了。我这里有的是下拉选择,使用 ajax 将值发布到另一个下拉列表,但现在我需要使用自动完成功能发布到文本框。我需要的是连接我的自动完成查询和我的ajax,这样如果我选择例如圆珠笔,所有圆珠笔都会在自动完成中推荐。请在这件事上给予我帮助。我需要完成它。
这是我的代码
Ajax.php
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
</head>
<body>
<br/>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag">
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').html(data);
}
});
});
</script>
getajax.php
在这里,我将值发布到另一个下拉列表中,但我不需要将值发布到文本框中。
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option value ="<?php echo $row['item_code'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
自动完成.php
<?php
//$q=$_GET['q'];
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
//$main = $mysqli->real_escape_string($_POST["mainlist_id"]); AND cat_code='$main'
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
最佳答案
//每当你选择标签字段时就会获得焦点,并且它会自动开始搜索,因此你无需键入 $(this).autocomplete("search", ""); 查看回调焦点函数;和 minlength 0。你必须发送主值并从这里获取响应
<script>
$(document).on("keyup", "#tag", function(){
$("#tag").autocomplete({
source: function(request, response) {
$.getJSON("autocomplete_gethere.php", { main: $("#main").val() }, response);
},
minLength:0
}).focus(function() {
$(this).autocomplete("search", "");
});
});
</script>
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#tag').focus(); //please note this, here we're focusing in that input field
}
});
});
</script>
未经测试,如有问题请评论
关于php - 根据数据库中下拉列表的值自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898753/