dousheyan0375 2012-11-17 19:04
浏览 115
已采纳

从mysql数据库中提供JQuery自动完成功能

I am trying to create an autocomplete field using JQuery, which receives its autocompletions from a mysql database.

Index.php:

        <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <script src="js/vendor/modernizr-2.6.2.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>
        <script type="text/javascript">
        $(function() {

            $("#college").autocomplete({
                source: "search.php",
                minLength: 2
            });
        });
        </script>
    </head>
    <body>

        <form action="<?php echo $_SERVER['PHP_SELF'];?>"  method="post">
            <fieldset>
            <legend>jQuery UI Autocomplete Example - PHP Backend</legend>

            <label for="state">State (abbreviation in separate field): </label>

            <input type="text" id="college"  name="college" />

            <input type="submit" name="submitBtn" value="Submit" />

            </fieldset>
        </form>

        <?php
if (isset($_POST['submit'])) {
echo "<p>";
    while (list($key,$value) = each($_POST)){
    echo "<strong>" . $key . "</strong> = ".$value."<br />";
    }
echo "</p>";
}
?>




        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->

        <!-- Add your site or application content here -->


        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
            (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
            g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
            s.parentNode.insertBefore(g,s)}(document,'script'));
        </script>
    </body>
</html>

search.php:

/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'college';

try {
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

$return_arr = array();

if ($conn)
{
    $ac_term = "%".$_GET['term']."%";
    $query = "SELECT * FROM college_list where name like :term";
    $result = $conn->prepare($query);
    $result->bindValue(":term",$ac_term);
    $result->execute();

    /* Retrieve and store in array the results of the query.*/
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $row_array['name'] = $row['name'];

        array_push($return_arr,$row_array);
    }


}
/* Free connection resources. */
//$conn = null; 
/* Toss back results as json encoded array. */
echo json_encode($return_arr);

?>

It's currently retrieving correctly from the database, because it's getting the correct number of autocompletions. However, they're all blank. It appears to not actually be feeding "name" back into the field and I can't seem to figure out why. Any ideas?

  • 写回答

1条回答 默认 最新

  • dongtang5229 2012-11-17 19:09
    关注

    Without seeing the autocomplete code you are using, I would say that you need a 1-dimensional array instead of a 2-dimensional one as you are generating now.

    You could try changing:

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $row_array['name'] = $row['name'];
    
        array_push($return_arr,$row_array);
    }
    

    To:

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        array_push($return_arr, $row['name']);
    }
    

    edit: check the api documentation, you need to build your array differently, something like:

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多