我正在使用带有PHP和MySQL获取数据的类别的自动完成:
PHP代码:
$sql ="SELECT categoria, name FROM categorias";
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
$categorias=json_encode($rows);
echo $categorias;
这会返回类似的内容:
[{"categoria":"Vendas","name":"Cat1"},{"categoria":"Fornecedores","name":"Cat2"}]
在JQuery中我有:
var categorias=[];
$.ajax({
url:"../categorias.php",
success: function(response){
categorias=response.split(",");
}
});
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
$inp.catcomplete({
delay:0,
source:categorias
})
但这不起作用。但是,如果我直接在JS中输入数据,例如:
var categorias= [
{ label: "Vendas", category: "Cat1" },
{ label: "Fornecedores", category: "Cat2" }]
效果很好,所以我如何以正确的格式从PHP获取数据:
答案 0 :(得分:1)
更新您的SQL语句以使用别名:
"SELECT categoria AS Label, name AS Category FROM categorias"