我正在尝试将自动完成功能添加到我的输入字段之一,一旦用户键入函数触发器并查询数据库以获取数字。
这是输入域代码
<div class="input-field col s12 m3 offset-m1 l2 offset-l1">
<input id="NumEmpleado" name="NumEmpleado" type="text" class="validate autocomplete" autocomplete="off" required="">
<label for="NumEmpleado">N° de Empleado</label>
</div>
这是脚本代码:
<script>
$(document).ready(function(){
$(document).on('input', 'input.autocomplete', function() {
let inputText = $(this).val(); //Gets text from input
$.get('suggest.php?key=' + inputText) //Makes the query
.done(function(suggestions) { //gets JSON data as suggestions
console.log(suggestions); //Prints
$('input.autocomplete').autocomplete({ //Initialize auto complete with new data
data: suggestions
});
});
});
});
</script>
这是 suggest.php - 当用户输入时触发
<?php
$key=$_GET['key'];
$NumEmpleado = array();
$conn = mysqli_connect('localhost', 'root', '', 'unacar');
$query= "select NumEmpleado from academico where NumEmpleado LIKE '%{$key}%'";
$res = mysqli_query($conn, $query);
if($res->num_rows>0){
while($row = $res->fetch_assoc()){
$NumEmpleado[trim($row["NumEmpleado"])] = null;
}
}
echo json_encode($NumEmpleado);
flush();
?>
到目前为止我已经注意到了这些事情:
当我在查看控制台时在输入字段上按空格键时,json 数据与数据库中的数据完全相同
当我按 1 时,它应该给我“31”作为唯一的自动完成选项,它显示 2 个选项,这不是来自 JSON 数据,出于某种原因,它试图显示图像(src:未知) .
还尝试加载一些东西
如果我输入 9,它应该给我 3 个选项; 9、93 和 98
感谢您的阅读,祝您有美好的一天。
最佳答案
Jquery 自动完成在初始化期间接受修复键和值(标签和值)。因此,首先,您必须将结果转换为特定的键值,如下所示。
$(document).ready(function(){
$( "#tags" ).autocomplete({
source: function(request, response) {
$.ajax({
url: 'suggest.php?key=' + $('#text_box_id').val(),
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item[0],
val: item[1]
}
}))
}
});
}
});
});
它可能对你有帮助。
关于javascript - 我的自动完成功能会忽略我的 JSON 数据并显示随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349357/