【问题标题】:Can't build Autocomplete textbox in PHP无法在 PHP 中构建自动完成文本框
【发布时间】: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


【解决方案1】:

自动完成默认 $_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
        }
    });
});

【讨论】:

  • 它似乎在内部工作,我检查了 XHR,它给出了 200 OK 状态(在它返回“已取消”状态之前)。但是文本框中没有显示任何内容。我添加了上面的代码并保留了 $_GET ['city'],并尝试将其更改为 $_GET['term'],而在 HTML 函数调用中也没有任何更改。没有结果。
猜你喜欢
  • 2017-07-03
  • 2016-02-20
  • 2011-08-03
  • 2020-05-17
  • 2016-01-20
  • 1970-01-01
  • 2012-05-21
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多