我正在尝试使用php和AJAX创建一个搜索框。但是,当我在搜索框中键入数据库中已有的名称时,不会显示任何建议。什么都没发生。
我测试了php并且似乎正在工作。我错过了什么?
使用PDO进行代码更新
require_once('connect_pdo.php');
$searchTerm = $_GET['term'];
$stmtus = $conn->prepare("SELECT * FROM `Schools` WHERE `School` LIKE :School");
$stmtus->bindValue(':School', '%' . $searchTerm . '%');
$searchTerm = $_POST['school'];;
$stmtus -> execute();
while ($result = $stmtus->fetch(PDO::FETCH_ASSOC)) {
$school = $result['School'];
}
echo json_encode($school);
AJAX
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#school").autocomplete({
source:'schoolfind.php',
minLength:3
});
});
</script>
HTML
<label>What school does the child attend<input type="text" name="school" id="school" /></label>
答案 0 :(得分:1)
您使用的任何绑定锚点(例如:School
)都需要在查询字符串中显示未加引号。即,不要这样做:
$stmtus = $conn->prepare("SELECT * FROM `Schools` WHERE `School` LIKE '%".$searchTerm."%'");
$stmtus->bindParam(':School', $searchTerm);
这样做:
$stmtus = $conn->prepare("SELECT * FROM `Schools` WHERE `School` LIKE :School");
$stmtus->bindValue(':School', '%' . $searchTerm . '%');