用于向类别提供JQuery自动完成的PHP代码

时间:2014-02-27 19:19:43

标签: javascript php jquery

我正在使用带有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获取数据:

  • 标签而不是“categoria”
  • 类别insteald of“name”

1 个答案:

答案 0 :(得分:1)

更新您的SQL语句以使用别名:

"SELECT categoria AS Label, name AS Category FROM categorias"