php - 无法在 PHP 中构建自动完成文本框

标签 php jquery mysql autocomplete

我一直在努力学习如何构建一个自动完成文本框,从我的数据库中获取城市,我使用 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/

相关文章:

javascript - 单击它时不显示选项

mysql - 需要一个想法来设计用于诊所预约安排的数据库 : "A doctor is working in multiple clinics in different timings"

javascript - JavaScript 中处理重复主键的模式

php - 如何使用 mysql 查询在我的数据库中仅查找特定的表和特定的列名

php - Insert Join with limit - Mysql

php - 手动更新 WordPress 数据库

php - 组合数字但不在 PHP 中添加它们

php - 为什么使用 iconv_strpos 而不是 strpos?

javascript - Jquery 复选框选择所有子项

javascript - 我需要使用链接文本作为 aria 标签将 aria-label 添加到网站上的所有链接