Typeahead和Bloodhound - 如何获得JSON结果

use*_*961 15 jquery json typeahead.js

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

而我正试图通过Bloodhound建议引擎获取country_id和国家名称.我试过以下代码:

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()
    });
Run Code Online (Sandbox Code Playgroud)

哪个不起作用.我该如何更改代码才能使其工作?

Jen*_*och 13

// 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()
});
Run Code Online (Sandbox Code Playgroud)

示例Codepen

预先输出

Typeahead的输出

笔记:

  • 您服务器上的数据="预取".
  • 来自外部的数据="远程"

  • 此解决方案不再有效.我自己尝试了,也尝试了你的codepen示例. (3认同)
  • 我道歉.说实话,我认为twitter放弃了typeahead.js.我们看看13000颗星,一个没有维护者和破坏软件的完整bugtracker,最后一个版本是2015年.我认为这说明了一下,不是吗?...所以,试试其中一个分叉:https://github.com/corejavascript/typeahead.js ---我相信他们已经解决了这个问题.没有测试过.感觉也可以自由修改我的codepen交换typeahead.js与fork的脚本.此致,Jens (2认同)