【问题标题】:Typeahead and Bloodhound - how to get JSON resultTypeahead 和 Bloodhound - 如何获取 JSON 结果
【发布时间】:2014-05-08 22:51:24
【问题描述】:

我有国家的 json 列表:http://vocab.nic.in/rest.php/country/json

我正在尝试使用 Bloodhound 建议引擎获取 country_id 和国家/地区名称。 O 尝试了以下代码:

var countries = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country_name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: 'http://vocab.nic.in/rest.php/country/json',
        filter: function(response) {
            return response.countries;
        }
    }
});

$('#my-input').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        displayKey: 'value',
        source: countries.ttAdapter()
    });

这不起作用。我应该如何更改代码以使其正常工作?

【问题讨论】:

标签: jquery json typeahead.js


【解决方案1】:
// instantiate the bloodhound suggestion engine
var countries = new Bloodhound({  
  datumTokenizer: function(countries) {
      return Bloodhound.tokenizers.whitespace(countries.value);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: "http://vocab.nic.in/rest.php/country/json",
    filter: function(response) {      
      return response.countries;
    }
  }
});

// initialize the bloodhound suggestion engine
countries.initialize();

// instantiate the typeahead UI
$('.typeahead').typeahead(
  { hint: true,
    highlight: true,
    minLength: 1
  }, 
  {
  name: 'countries',
  displayKey: function(countries) {
    return countries.country.country_name;        
  },
  source: countries.ttAdapter()
});

Example Codepen

Typeahead 输出

注意事项:

  • 您服务器上的数据 = “预取”。
  • 来自外部的数据 =“远程”

【讨论】:

  • 在 datumTokenizer 中我使用了 countries.countries,它必须是 countries.value。相应地更新了代码和 Codepen。 Chrome 对我来说是小丑,使用 firefox :)
  • 此解决方案不再有效。我自己试过了,也在你的 codepen 例子上试过。
  • 没错,停止工作。嗯,一岁多了。我猜,其中一个 API 又发生了变化。
  • 我知道这已经有一段时间了,codepen 似乎不再工作了......尝试搜索“保加利亚”。我得到的列表和你的截图一样。
  • 我很抱歉。老实说,我认为 twitter 放弃了 typeahead.js。我们查看了 13000 颗星,一个没有维护者的完整 bugtracker 和一个损坏的软件,最后一个版本是 2015 年。我认为这不言自明? ...所以,尝试其中一个分支:github.com/corejavascript/typeahead.js --- 我相信他们解决了这个问题。未测试。也可以随意修改我的 codepen,将 typeahead.js 与 fork 的脚本进行交换。问候,延斯
【解决方案2】:

注意:如果您执行了所有这些操作但仍然无法正常工作,请检查您的 data.json 文件(无论您将其命名为什么)

良好格式的示例: https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json

['data1','data2',.....]

我被不合适的报价绊倒了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多