将json编码数组中的项添加到自动完成输入框中


Add items from json encoded array to auto complete input box

我有一个php文件,返回一个json编码的数组,我想显示json数组中的项目,以便在自动完成搜索框中显示。我在search3.php中的代码是:

<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
    echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$return_arr = array();
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
    $output = '<div>No results!</div>';
}else{
    while($row = mysqli_fetch_array($query)){
        $orgname = $row['Organisation_Name'];
        $orgid = $row['Organisation_Id'];
        $return_arr[] = $row['Subscription_Type'];
        //$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
        $output = $orgname; 
        $output2 = $orgid; 
        $output3 = $subs;
        //$output = '<div>'.$orgname.'</div>';
    }
}
}
echo json_encode($return_arr);
?>

我使用这个javascript将json中的项目添加到输入框中,以显示自动完成的项目。

<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
    source: "search3.php",
    minLength: 1
});                
});
</script>

输入字段如下:

Search: <input class="auto" type="text" required name="search">

我做错了什么?

您需要首先将JSON作为字符串获取,然后才能使用该字符串作为自动完成函数的源

$.ajax({
  url: "source3.php",
  cache: false,
  success: function(json_string){
   $(".auto").autocomplete({
     source: json_string,
     minLength: 1
   });           
  }
});

如果您想在密钥事件上获取json,请尝试以下操作(请参阅远程json数据源):-

  <script>
 $(function() {
function log( message ) {
  $( "<div>" ).text( message ).prependTo( "#log" );
  $( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "http://gd.geobytes.com/AutoCompleteCity",
      dataType: "jsonp",
      data: {
        q: request.term
      },
      success: function( data ) {
        response( data );
      }
    });
  },
  minLength: 3,
  select: function( event, ui ) {
    log( ui.item ?
      "Selected: " + ui.item.label :
      "Nothing selected, input was " + this.value);
  },
  open: function() {
    $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
});

});

建议您必须使用AJAX函数。

使用以下jquery代码:

$(document).ready(function(){
    $(".auto").keyup(function(){
        $.ajax({
        type: "POST",
        url: "source3.php",
        data:'searchVal='+$(this).val(),
        success: function(data){
            var json_string = $.parseJSON(data);
            $(".auto").autocomplete({
             source: json_string,
             minLength: 1
            }); 
        }
        });
    });
});

有关更多详细信息,请查看此。