【问题标题】:JQuery Autocomplete with PDO Statements带有 PDO 语句的 JQuery 自动完成
【发布时间】:2016-10-18 22:05:59
【问题描述】:

我很难找到这个错误。我花了大约 10 个小时搜索和测试,但谷歌无法为我提供任何东西。所以你们是我最后的希望。 我有一个简单的 html 文本字段:

 <input type="text" value="" id="keyword" name="zip" placeholder="Please enter ZIP code" required>

这是我的 Javascript 代码(JQuery 文件链接正确,不用担心):

var MIN_LENGTH = 2;
    $( document ).ready(function() {
        $("#keyword").keyup(function() {
            var keyword = $("#keyword").val();
            if (keyword.length >= MIN_LENGTH) {
                $.get( "autocomplete", { keyword: keyword } )
                    .done(function( data ) {
                        console.log(data);
                    });
            }
        });
    });

当我在文本字段中输入值“sw”时,我会在控制台中得到以下结果:

["Swaziland\r","Sweden\r","Switzerland\r"]

应该是正确的。这是我的第一个问题。 “\r”正常吗? 而我的第二个也是更重要的问题是:如何添加查询功能自动完成?我的目标类似于以下示例:https://jqueryui.com/autocomplete/

请帮助我,我测试了很长时间,但我无法找到解决方案。我认为这是一个有点愚蠢的错误。 这里是所有文件:

自动完成.php

if (!isset($_GET['keyword'])) {
    die();
}
$keyword = $_GET['keyword'];
$data = SQL::searchForKeyword($keyword);
echo json_encode($data);

searchForKeyword 函数:

static function searchForKeyword($keyword) {
    $stmt = self::getInstance()->_conn->prepare("SELECT NameCountry as countries FROM `country` WHERE NameCountry LIKE ? ORDER BY countries");
    $keyword = $keyword . '%';
    $stmt->bindParam(1, $keyword, PDO::PARAM_STR, 100);
    $isQueryOk = $stmt->execute();
    $results = array();
    if ($isQueryOk) {
        $results = $stmt->fetchAll(PDO::FETCH_COLUMN);
    } else {
        trigger_error('Error executing statement.', E_USER_ERROR);
    }
    return $results;
}

【问题讨论】:

    标签: javascript php jquery autocomplete


    【解决方案1】:

    jQuery ui 文档的关键在于找到正确的页面。
    您需要的是 Remote jsonp datasource 示例。

    我在remote datasource 示例上浪费了很多时间(我什至无法运行),因为我害怕“p”...

    所以here is my version,稍微增强了一个动态加载自动完成下拉列表的示例。
    我希望它能帮助很多人。

    有趣的是,我没有像 jQuery 文档建议的那样使用 jsonp。
    它会在控制台中产生一个奇怪的不清楚的错误:

        Error: jQuery112409377035747123055_1476875409950 was not called(…)

    <!doctype html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>jQuery UI Autocomplete - Remote datasource</title>
            <link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
    
            <style>
                .ui-autocomplete-loading {
                    background: white url("ajax-loader.gif") right center no-repeat;
                }
                .ui-widget{
                    width:500px;
                }
                .ui-front{
                    width:10em;
                    background-color:#bebebe;
                }
                #log{
                    height: 200px;
                    width: 500px;
                    overflow: auto;
                }
                #noResult{
                    display:none;
                    color:red;
                    padding-left:1em;
                }
            </style>
            <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script>
                $( function() {
                    function log( message ){
                        $( "<div>" ).text( message ).appendTo( "#log" );
                        $("#UScities").blur();
                    }
    
                    $( "#UScities" ).autocomplete({
                        source: function( request, response ) {
    
                            $.ajax({
                                url: "search.php",
                                data: {keyword:request.term},
                                dataType: 'json',               // DON'T use jsonp !
                                cache: false,
                                success: function(data){
    
                                    console.log(data);
    
                                    // Even on success, it may have no results...
                                    if(typeof(data[0])!="undefined"){
    
                                        // Remove the no result error in case it's displayed
                                        $("#noResult").css("display","none");
    
                                        // For fun, count it!
                                        var count = 0;
                                        while (data[count]) {
                                            console.log(data[count]);
                                            count++;
                                        }
                                    }else{
                                        count = "NO";
                                        // Display the no result error
                                        $("#noResult").css("display","inline");
                                    }
    
                                    console.log(count+" RESULTS");
    
                                    // Pass the data to the dropdown!
                                    response(data);
                                },
                                error: function(jqXHR, textStatus, errorThrown){
                                    console.log(errorThrown);
                                }
                            });
    
                        },
                        minLength: 4,
                        select: function( event, ui ) {
                            log( ui.item.value );
                        }
                    });
    
                    // Show results on input focus
                    $("#UScities").on("focus",function(){
                        $("#ui-id-1").css("display","block");
                    });
                });
    
            </script>
        </head>
        <body>
    
            <div class="ui-widget">
                <label for="UScities">USA cities: </label>
                <input type="text" id="UScities"><span id="noResult">No Result</span><br>
            </div>
    
            <div class="ui-widget" style="margin-top:2em; font-family:Arial">
                <div id="log" class="ui-widget-content"></div>
            </div>
    
        </body>
    </html>
    

    我在控制台中添加了结果计数(可用于触发某些事情)并向用户添加“NO RESULT”消息,因为关键字搜索可能没有结果。

    现在,jQuery 文档中非常缺乏的是如何生成 json 输出。

    <?php
    if (!isset($_GET['keyword'])) {
        // Do nothing if no keyword!
        die();
    }
    
    // Database connection infos (PDO).
    $dsn = 'mysql:dbname=[Database Name];host=localhost';
    $user = '[Database User]';
    $password = '[UserPassword]';
    
    try {
      $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
      echo 'Connexion failed : ' . $e->getMessage();
    }
    
    // Getting the keyword and add % to get data that begins with it.
    $keyword = $_GET['keyword'] . '%';
    
    // If you want the keyword to be "contained" in the data, use (uncomment it):
    //$keyword = '%' . $_GET['keyword'] . '%';
    
    // Query.
    $query = "SELECT city FROM SO_USAzipcodes WHERE city LIKE ? GROUP BY city limit 30";
    
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(1, $keyword);
    
    // Executing.
    $stmt->execute();
    
    // If SQL error...
    if (!$stmt) {
       echo "\nPDO::errorInfo():\n";
       print_r($dbh->errorInfo());
       die();
    }
    
    // Fetching.
    $data = array();
    $data = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // This is sending the json to autocomplete.
    echo json_encode( $data );
    ?>
    

    如果您在此文件中有语法错误...
    或者如果由于 DB 连接或 SQL 语法错误而出现错误...

    你会在控制台中得到这样的东西:

    SyntaxError: Unexpected token < in JSON at position 0(…)
    

    主页上什么也没有发生,但旋转的.gif 一直在转动。顺便说一句,我刚刚发现了这个值得一看的loading gif generator。 ;)

    【讨论】:

    • 我会尝试并告诉你,但是已经非常感谢你了!!
    • 所以我试了一下。我的问题又来了。我总是收到“SyntaxError: Unexpected token " 但这似乎不起作用 =( 有什么建议吗?
    • 您遇到的这个错误是因为您的 autocomplete.php 正在抛出错误而不是 json。直接访问它以完全查看错误(使用完整路径+关键字,如@9​​87654331@)或检查文件所在目录中的error.log文件...进行调试,回显您的变量...
    • 你是我的英雄!非常感谢,你是对的!
    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多