2016-07-27 86 views
0

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

<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); 
    ?> 
+0

什么是你的问题? –

+0

你忘了在查询中添加$ searchTerm。 –

回答

0
$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); 
+0

我编辑了代码buth仍然不能正常工作 – parvez

+0

什么是DB中的分类列名,在哪里替换条件 –

+0

分类列名是'country' – parvez

0

相反的:

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

您需要在您的查询的$searchTerm,有点像:

$searchTerm = $_GET['term']; 

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

OR

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

我编辑了代码buth仍然没有工作 – parvez