简体   繁体   English

Typeahead.js,获取远程数据后搜索不起作用

[英]Typeahead.js, Searches Don't Work After Fetching Remote Data

Typeahead.js is not updating the search index after requesting remote data. Typeahead.js 在请求远程数据后不更新搜索索引。

I type a query, it fetches results, and then it always displays the first N items without respect to the query.我键入一个查询,它获取结果,然后它总是显示前 N 个项目,而不考虑查询。 I have used the bloodhound_inst.search('lemon', sync, async) function in the console and it's returning the entire remote dataset regardless of any text match.我在控制台中使用了bloodhound_inst.search('lemon', sync, async)函数,无论文本匹配如何,它都会返回整个远程数据集。

For example this query will return 'apple', 'pizza', anything that comes back from the server.例如,此查询将返回“apple”、“pizza”以及从服务器返回的任何内容。

I am expecting it to fetch remote data and then provide search results like normal.我希望它能够获取远程数据,然后像往常一样提供搜索结果。 Is it expecting the remote to provide the correct data?是否期望遥控器提供正确的数据? I am just passing a test list of items from the server ['lemon', 'banana', 'apple', 'whatever'] as the response.我只是通过服务器['lemon', 'banana', 'apple', 'whatever']的项目测试列表作为响应。

<script>
  var food_name= '<%= @food.name %>';

  var food_items = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: '../food_item_search?food_name_q=%QUERY',
      wildcard: '%QUERY'
    }
  });

  var engine = food_items.initialize(true);

  $('.typeahead').typeahead(null, {
    limit: 7,
    source: food_items
  })

</script>

You guessed it.你猜对了。 It is expecting the remote to perform the search.它期望遥控器执行搜索。

If you wanted to load all the data in and then have it search that data for you, you would use local, not remote.如果您想加载所有数据,然后让它为您搜索该数据,您将使用本地,而不是远程。 I accomplished that like this:我是这样完成的:

ajaxGet('/manage/persontypeahead')
    .done(function (r) {
        applyNamesTypeahead(r.ViewModel);
    });

Where applyNamesTypeahead consumes the loaded data and builds the Bloodhound:其中 applyNamesTypeahead 使用加载的数据并构建 Bloodhound:

function applyNamesTypeahead(local) {
    var namesBloodhound = new Bloodhound({
        local: local,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Name')
    });

then, builds the Typeahead:然后,构建 Typeahead:

    $('#Name').typeahead({
        hint: true,
        classNames: {
            menu: 'dropdown-menu',
            suggestion: 'dropdown-item',
            cursor: 'active'
        }
    }, {
        source: namesBloodhound,
        display: 'Name'
    });

I included the classNames here to show how we're using standard Bootstrap 5 to render the Twitter Typeahead, without having to custom style it.我在此处包含了 classNames,以展示我们如何使用标准 Bootstrap 5 来呈现 Twitter Typeahead,而无需自定义样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM