我正在使用具体化自动完成功能从我的数据库表中获取建议列表。我将源代码提供为 php 文件,在其中回显 json 文件。下面是代码。它不起作用。为什么?
index.php
<div class="input-field ">
<input type="text" name="t" id="t" class="autocomplete">
</div>
<script>
$(function () {
$('input.autocomplete').autocomplete({
source: 'suggest.php?key=%QUERY'
});
});
</script>
建议.php
<?php
$key=$_GET['key'];
$array = array();
$conn = mysqli_connect('localhost', 'root', '', 'home_services');
$query= "select * from worker where lname LIKE '%{$key}%'";
$res = mysqli_query($conn, $query);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
$lname[]= trim($row["lname"]);
}
}
echo json_encode($lname);
?>
最佳答案
Materialize 自动完成功能没有自动加载提供的 URL 的 source
选项。
当您查看documentation时您可以看到您必须像这样初始化自动完成功能:
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
data
选项接受带有可选图标字符串的字符串名称。
您需要在初始化自动完成之前提取自动完成数据,并在初始化时向其提供数据:
$(document).ready(function(){
$(document).on('input', 'input.autocomplete', function() {
let inputText = $(this).val();
$.get('suggest.php?key=' + inputText)
.done(function(suggestions) {
$('input.autocomplete').autocomplete({
data: suggestions
});
});
});
});
此外,您还需要调整 suggest.php
以生成自动完成的 data
选项所需格式的 JSON。所以你需要像这样更改你的代码:
while($row = $res->fetch_assoc()){
$lname[trim($row["lname"])] = null;
}
编辑:您还可以使用名称 $array
初始化数组,但将内容添加到名为 $lname
的不存在数组中。您应该将 $array = array();
更改为 $lname = array();
关于php - 使用 php、mysql 和 jQuery 实现自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52604003/