jQuery UI自动完成类别

时间:2010-10-10 01:25:43

标签: jquery jquery-ui autocomplete categories

我正在使用jQuery UI的自动完成功能来从远程源提供搜索输入框的建议。我有“远程数据源”示例正常工作。例如,这有效:

    $("#search").autocomplete({
        source: "search_basic.php",
        minLength: 2
    });

但是,我想使用“Categories”示例按类别对建议进行排序。来自jQuery UI站点的示例,带有内联数据集的工作正常:

       <script>
 $.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 );
   });
  }
 });

 $(function() {
  var data = [
   { label: "anders", category: "" },
   { label: "andreas", category: "" },
   { label: "antal", category: "" },
   { label: "annhhx10", category: "Products" },
   { label: "annk K12", category: "Products" },
   { label: "annttop C13", category: "Products" },
   { label: "anders andersson", category: "People" },
   { label: "andreas andersson", category: "People" },
   { label: "andreas johnson", category: "People" }
  ];

  $( "#search" ).catcomplete({
   delay: 0,
   source: data
  });
 });
 </script>

但是,当我尝试从远程文件中获取数据时

source: 'search.php'

它没有任何暗示。这是search.php的代码:

    <script>
 $.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 );
   });
  }
 });

 $(function() {

  $( "#search" ).catcomplete({
   source: 'search.php'
  });
 });
 </script>

search.php返回的数据格式正确:

         [
 { label: "annhhx10", category: "Products" },
 { label: "annttop", category: "Products" },
 { label: "anders", category: "People" },
 { label: "andreas", category: "People" }
 ]

非常感谢任何帮助!

谢谢, 格雷格

2 个答案:

答案 0 :(得分:6)

自从我迁移到UI 1.10.2后,我的小部件无效!

只是修改了一行:

self._renderItem( ul, item );

变为:

self._renderItemData( ul, item );

再次有效!

答案 1 :(得分:1)

你的PHP文件可能没有返回正确的标题。将其添加到您的PHP文件中:

header('Content-Type: application/json');

然后,浏览器会将响应解释为JSON并对其进行操作。

修改

在响应中返回JSON时,您的响应还需要在标签周围加上引号,而不仅仅是值。 在PHP中,在对象数组上使用json_encode()将返回以下JSON(添加了换行符):

[
 { "label": "annhhx10", "category": "Products" },
 { "label": "annttop", "category": "Products" },
 { "label": "anders", "category": "People" },
 { "label": "andreas", "category": "People" }
]