2016-10-18 9 views
-1

このエラーを見つけるのは苦労しています。私は約10時間の検索とテストを費やしましたが、Googleでは何も提供できませんでした。あなたたちは本当に最後の希望です。 私は単純なHTMLテキストフィールドを持っている:PDOステートメントを使用したJQueryオートコンプリート

<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"は普通ですか? もう1つ重要なのは、クエリ関数のオートコンプリートを追加するにはどうすればいいですか?私の目標は次の例のようになります:https://jqueryui.com/autocomplete/

私は長い間テストしましたが解決策を見つけることができません。そして私はそれが少しばかげたエラーだと思う。 ここでは、すべてのファイル:

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; 
} 

答えて

1

jQueryのUIのドキュメントを持つ事は、右のページを見つけることです。
必要なものはRemote jsonp datasourceの例です。

私は「P」でaffraidたので、私は、そうhere is my version、強化ちょっと...、(WICH私も実行することができていない)remote datasource例に

を多くの時間を失いましたautocompleteドロップダウンを動的にロードする例を示します。
多くの人々に役立つことを願っています。

面白いのは、は、jQueryドキュメントのようにjsonpを使用していないということです。 「NO、私は(何かをトリガするために使用することができる)コンソールでの結果数を追加しました

        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> 

と:
それは奇妙な不明瞭なコンソールでエラーが発生しますキーワード検索で結果を得ることができないため、「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を発見しました。 ;)

+0

私はすでに大きなありがとうしかし、それを試してみて、あなたが知っているだろう! – jor

+0

私はそれを試しました。もう一度私の問題。私はいつも "SyntaxError:予期せぬトークン」しかし、このdoesntのは、任意の提案(=動作するようには思え – jor

+0

あなたautocomplete.phpがエラーをtrowing代わりにされているので、あなたが持っているこのエラーは次のとおりです。URL:そのような? 。JSON完全に(? 'httpsのような完全なパス+キーワード使用://www.bessetteweb.com/SO/40118887/search.phpキーワード= mass')のエラーを見て、それを直接アクセスするかをチェックし、' error.log'ファイルがある...デバッグに、あなたのVARSをエコーディレクトリ内のファイル... –

関連する問題