【问题标题】:autocomplete with category in php mysql is not workingphp mysql中的类别自动完成功能不起作用
【发布时间】:2016-07-27 13:02:58
【问题描述】:

我想做的是通过 jQueryUI 的功能使用自动完成对结果进行分类。经过一番谷歌搜索后,我发现它有一个内置函数(http://jqueryui.com/demos/autocomplete/#categories),但该示例仅适用于本地数据源(javascript 中的数组)。我正在处理一个远程数据源。 我的代码是

<script>
$( function() {
 $.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
    var self = this,
        currentCategory = "";
    $.each(items, function(index, item) {
        if (item.category != currentCategory) {
            ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
            currentCategory = item.category;
        }
        self._renderItem(ul, item);
    });
}
});
$( "#search" ).catcomplete({
    delay:0,
    source: "search.php",
    select: function(event, ui){
    alert(ui.item.label);
}
});
} );
 </script>
 </head>
 <body>
<label for="search">Search: </label>
<input id="search">
</body> 

这里是 search.php

<?php
 $conn = mysqli_connect("localhost","root","","test") or die(mysqli_error());
 $searchTerm = $_GET['term'];
 $sql = "select * from country_ref_table where country_code LIKE '%".$searchTerm."%' ORDER BY country_code ASC";
 $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
 $data = [];
 while($row = mysqli_fetch_array($result))
  {
   $data[] = $row['country_code'];
   $data[] = $row['country'];
  }
 echo json_encode($data);
  ?>

【问题讨论】:

  • 你有什么问题?
  • 您忘记在查询中添加 $searchTerm。

标签: php mysql jquery-ui jquery-ui-autocomplete


【解决方案1】:

代替:

 $searchTerm = $_GET['term'];
 $sql = "select * from country_ref_table";

您需要在查询中包含$searchTerm,有点像:

$searchTerm = $_GET['term'];

$sql = "select * from country_ref_table WHERE `columnTerm` LIKE '%".$searchTerm ."%' ";

$sql = "select * from country_ref_table WHERE `columnTerm` = '$searchTerm' ";

【讨论】:

    【解决方案2】:
     $searchTerm = $_GET['term'];
     $sql = "select * from country_ref_table";
    

    在 $sql 中添加

     $sql = "select * from country_ref_table where `term` LIKE '%".$searchTerm ."%'";
    

    然后使用这样的数据:

    $data=array();
    while($row = mysqli_fetch_array($result))
      {
       $data[]['id'] = $row['country_code'];
       $data[]['category'] = $row['country'];
      }
     echo json_encode($data);
    

    【讨论】:

    • 你在DB中的分类列名是什么,在where条件下替换
    • 分类列名是country
    • 然后使用这个: $sql = "select * from country_ref_table where country LIKE '%".$searchTerm ."%'";
    • $data=array(); while($row = mysqli_fetch_array($result)) { $data[]['id'] = $row['country_code']; $data[]['category'] = $row['country']; } echo json_encode($data);
    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2017-02-28
    • 2020-11-14
    • 2014-03-11
    • 2014-01-16
    • 2011-03-14
    相关资源
    最近更新 更多