我对自动完成输入有疑问。
有php代码。
<?php
$db = mysqli_connect("localhost", "username", "password", "mydb");
if ($db === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
} else {
echo "<script>console.log('Polaczenie z baza nawiazane');</script>";
}
$searchTerm = $_GET['term'];
$query = $db->query("SELECT email FROM users WHERE email LIKE '%" . $searchTerm . "%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['email'];
}
//return json data
echo json_encode($data);
// close connection
mysqli_close($db);
?>
这是我的输入字段。
<input id="email">
和jquery
<script>
$(function() {
$( "#email" ).autocomplete({
source: 'test.php'
});
});
</script>
问题是我直接在页面上获取Json-我想要一个带有提示的简单输入框(自动完成) 怎么了?
答案 0 :(得分:1)
从PHP发送Content-Type
时,您似乎缺少了response
标头信息。
我还注意到您在回显后关闭了mysqli连接。它需要反过来。首先关闭mysqli连接,然后回显。
在下面检查更改的PHP代码,
$db = mysqli_connect("localhost", "username", "password", "mydb");
if ($db === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
} else {
echo "<script>console.log('Polaczenie z baza nawiazane');</script>";
}
$searchTerm = $_GET['term'];
$query = $db->query("SELECT email FROM users WHERE email LIKE '%" . $searchTerm . "%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['email'];
}
// close connection
mysqli_close($db);
// adding content type header
header('Content-Type: application/json');
//return json data
echo json_encode($data);
希望这会有所帮助,
干杯。