我一直在努力学习如何构建一个自动完成文本框,从我的数据库中获取城市,我使用 XAMPP,所以它是 mySQL。以下是我从教程中提取并根据需要修改的代码:
演示.html
<html>
<head>
<title>Autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#city" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="city">Region: </label>
<input id="city">
</div>
</body>
</html>
搜索.php
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'sample_master';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['city'];
//get matched data from skills table
//"region" is the column from the table I wish to fetch
$query = $db->query("SELECT * FROM cities WHERE region LIKE '%".$searchTerm."%' ORDER BY region");
while ($row = $query->fetch_assoc()) {
$data[] = $row['region'];
}
//return json data
echo json_encode($data);
?>
在 xampp 中,我启动 MySQL 和 Apache 服务器,然后从 htdocs 打开 demo.html。自动完成功能不起作用(我输入时没有显示任何内容)。我究竟做错了什么?此外,城市数据库有超过 3,00,000 条记录。
最佳答案
自动完成默认 $_GET 是 $_GET['term'] ,你叫 $_GET['city'] 所以你需要改变你的 $_GET 名字或者你可以像下面这样定义你的 GET 名字..
$(function() {
$( "#city" ).autocomplete({
source: function(r,res){
$.get('search.php',{city:r.term},res,'json');//r is input typing request,res is response result as json
}
});
});
关于php - 无法在 PHP 中构建自动完成文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38050257/