jQueryUI自动完成功能未正确过滤JSON文件的结果

时间:2013-05-19 00:19:05

标签: jquery jquery-ui

我已经在我的测试网站http://karem.kaidez.com/上使用自动完成小部件配置了一个支持jQueryUI的搜索。数据由.json文件填充,当我根据我在搜索框中输入的内容对其进行过滤时,所有结果都会显示。

搜索框嵌入在HTML中,如下所示:

<input type="text" id="searchfield" class="searchfield-style" placeholder="Search..." />

具体的jQueryUI代码如下所示:

  define("search", ["jquery","jqui"], function($, jqui) { //running via RequireJS
  $("#searchfield").autocomplete({
    source: function( request, response ) {
      $.ajax({
        url: "search.json",
        dataType: "json",
        data: {term: request.term},
        success: function(data) {
          response($.map(data, function(item) {
            return {
              label: item.title
            };
          }));
        }
      });
    },
    minLength: 0,
    select: function(event, ui) {
     //code comes later
    }
  });
});

search.json看起来像这样:

[

  {
    "title":"lorem",
    "url":"/lorem/"
  },

  {
    "title":"ipsum",
    "url":"/ipsum/"
  },

 false
 /*
  * This 'false' is here because the JSON file is being built via a Jekyll 
  * plugin and adding commas at the end of the final key/value pait.
  * Adding 'false' makes the file valid JSON. 
  */

]

我确实看到了另外这个问题/答案here,我认为我确保正确配置了这个术语参数。我想认为修复很简单但不确定。

1 个答案:

答案 0 :(得分:0)

try this

    ('#searchfield').autocomplete({
        source: function( request, response ) {
  $.ajax({
    url: "search.json",
    dataType: "json",
    data: {term: request.term},
    success: function(data) {
      response($.map(data, function(item) {
        return {
          label: item.title
        };
      }));
    }
  });
},
        minLength: 2,
        search: function(oEvent, oUi) {
            var selectedValue = $(oEvent.target).val();
            var aSearch = [];
            $('source').each(function(index, value) {
                if (value.substr(0, selectedValue .length) == selectedValue ) 
                    aSearch.push(value);               
            });

            $(this).autocomplete('option', 'source', aSearch);
        }
    });