jQuery UI自动完成类别

use*_*262 7 jquery jquery-ui autocomplete categories

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

    $("#search").autocomplete({
        source: "search_basic.php",
        minLength: 2
    });
Run Code Online (Sandbox Code Playgroud)

但是,我想使用" 类别 "示例按类别对建议进行排序.来自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>
Run Code Online (Sandbox Code Playgroud)

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

source: 'search.php'
Run Code Online (Sandbox Code Playgroud)

它没有任何暗示.这是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>
Run Code Online (Sandbox Code Playgroud)

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

         [
 { label: "annhhx10", category: "Products" },
 { label: "annttop", category: "Products" },
 { label: "anders", category: "People" },
 { label: "andreas", category: "People" }
 ]
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

谢谢,格雷格

小智 6

自从我迁移到UI 1.10.2后,我的小部件无法正常工作!

只是修改了一行:

self._renderItem( ul, item );
Run Code Online (Sandbox Code Playgroud)

变成:

self._renderItemData( ul, item );
Run Code Online (Sandbox Code Playgroud)

那再次有效!


Cla*_*son 1

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

header('Content-Type: application/json');
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

[
 { "label": "annhhx10", "category": "Products" },
 { "label": "annttop", "category": "Products" },
 { "label": "anders", "category": "People" },
 { "label": "andreas", "category": "People" }
]
Run Code Online (Sandbox Code Playgroud)