单击建议结果并填写文本框

时间:2016-01-24 06:32:44

标签: javascript php jquery

我有一个搜索框,根据MySql数据库中的数据为您提供建议结果列表。如果用户输入A并且数据库中包含单词AppleAnimal,则建议框将显示两个结果。目前,我没有办法点击其中一个结果并填写文本框,无论我尝试做什么,我似乎无法让它工作。目前,我正在使用看起来像这样的东西:

  echo '<script type ="text/javascript">'; 

  echo 'function textFill(){';
  echo ' var txt=document.getElementById("userInput").value= <li onclick ="textFill(this.value)">' .$matched[$count].'</li>'; //Suggestion results
  echo '}';
  echo"</script>";
 }

我会说实话,我不确定这是否是正确的道路,但我发现了一些与此模糊相似的例子,所以这就是我的方向。通过此设置,建议框甚至不会显示,但如果我带走了echo '<script type ='text/javascript>',它将显示结果加上getElement代码的整行。我该如何才能让它正常工作?如有必要,我可以显示更多代码。

编辑: 我提供了更多代码来展示我的PHP:

if(isset($_GET['userInput'])){
   $value = $_GET['userInput']; //assign the value
   strtolower($value);
  }else{
   echo "no input";
  }
//Select query

  $sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '%".$value."%';";


  if($result = mysqli_query($conn, $sql)){
   if(mysqli_num_rows($result) > 0){ 
//Store the result in an array list[]

     while($row = mysqli_fetch_array($result)){
     $list[] = $row['Device_type'];
    }
   }else{
//set a null value to list[] if no result to prevent error

    $list[] = "";
   }
  }

  if(!empty($value)){
   if($matched = preg_grep('~'.$value.'~i', $list)){
   $count = 0;
   echo '<ul>';
    while($count < sizeOf($list)){
     if(isset($matched[$count])){

      echo '<li > ' .$matched[$count].'</li>';

     }
     $count++;
    }
   echo '</ul>';
   echo json_encode($data);
   }else{
    echo "No result";
   }

1 个答案:

答案 0 :(得分:0)

假设您的网络服务器提供了以下文件。

|- search.php
|- index.html

在index.html文件中:

<!-- loading JQuery library -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<!-- code for capturing user input, sending it to server (search.php) and upon receiving suggestions populating them under the search box -->
<script>
$(document).ready(function() {
    $('#searchbox').keyup(function() { // upon every key up when user is typing
        $('#suggestions').html(''); // clear if any previous suggestions

        var input = $(this).val();

        $.getJSON( // sending a GET request via AJAX expecting a JSON response
            'search.php', // to this URL where the PHP file is
            {
                searchQuery: input // with the text user typed in
            },
            function(data) { // upon receiving a response
                $(data).each(function() { // iterate through the suggestions data received as JSON
                    var suggestion = '<option value=' + this + '>'; // create an <option> element with the each suggestion
                    $('#suggestions').append(suggestion); // and append it to the suggestions <datalist>
                });
            }
        });
    });
});
</script>

<!-- search form -->
<input id="searchbox" name="searchbox" type="search" list="suggestions">
<datalist id="suggestions">
    <!-- suggestions will be populated here when user is typing -->
</datalist>

您的search.php文件:

$term = $_GET['searchQuery'];
$suggestions = [];

if(isset($term) && !empty($term)){
    $servername = "your_db_servername"; // Ex: localhost
    $username = "your_db_username"; // Ex: root
    $password = "your_db_password";
    $dbname = "your_db_name";

    $conn = mysqli_connect($servername, $username, $password, $dbname);
    if(!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '". $term ."%';"; 
    $result = mysqli_query($conn, $sql);

    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_array($result)) {
            array_push($suggestions, $row["Device_type"]);
        }
    }

    mysqli_close($conn);

    echo json_encode($suggestions);
}

但是你应该注意,在evey keyup事件上发送AJAX请求可能会非常压倒性,特别是如果用户输入速度很快。

为了提高效率,最好去掉keyup事件。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js "></script>
<script>
$(document).ready(function() {
    $('#searchbox').keyup($.debounce( 250, function() { // act upon keyup events every 250 milliseconds when user is typing 
        $('#suggestions').html('');

        var input = $(this).val();

        $.getJSON(
            'search.php',
            { searchQuery: input },
            function(data) {
                $(data).each(function() {
                    var suggestion = '<option value=' + this + '>';
                    $('#suggestions').append(suggestion);
                });
            }
        );
    }));
});
</script>