简体   繁体   English

使用 jQuery、PHP 和 MySQL 自动完成输入

[英]Autocomplete input using jQuery, PHP and MySQL

I have a question about autocomplete input.我有一个关于自动完成输入的问题。

There is php code.有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);

?>

there is my input field.有我的输入字段。

<input id="email">

and jquery和jQuery

<script>
$(function() {
    $( "#email" ).autocomplete({
        source: 'test.php'
    });
});
</script>

Problem is that I am getting Json directly on my page - I want to have simple input box with hints(autocomplete) What's wrong?问题是我直接在我的页面上获取 Json - 我想要带有提示的简单输入框(自动完成) 怎么了?

Looks like you are missing Content-Type header information when sending the response from PHP.从 PHP 发送response时,您似乎缺少Content-Type标头信息。

I have also noted that you are closing the mysqli connection after the echo.我还注意到您在回声后关闭了 mysqli 连接。 It needs to be the other way around.它需要反过来。 First close the mysqli connection and then echo.先关闭mysqli连接,然后回显。

Check the changed PHP code below,检查下面更改的 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);

Hope this helps,希望这可以帮助,

Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM