【发布时间】:2016-10-29 05:58:39
【问题描述】:
我一直在尝试学习如何构建一个从我的数据库中获取城市的自动完成文本框,我使用 XAMPP,所以它是 mySQL。以下是我从教程中挑选并根据需要修改的代码:
demo.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 条记录。
【问题讨论】:
-
在浏览器检查器中检查网络流量。 XHR 请求是否触发到 search.php,响应是什么?
-
@AronCederholm 当我输入时它会触发对 search.php 的查询,但它们显示已取消状态。
标签: php jquery mysql autocomplete