2016-07-27 88 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