如何让 typeahead JS 与我的 json 文件一起工作

How to get typeahead JS working with my json file

我想用 Typeahead JS 做一个简单的自动完成,但我做不到。我按照手册中的说明进行操作,但我不确定我在这里做错了什么。我无法从 json 文件中获取正确的值。它是一个包含对象的数组,我只想要国家名称。我认为不应该那么难。我没有显示任何东西。请帮忙! 您可以在 Typeahead Github 页面的 "Getting Started" 找到 typeahead js 文件。

这是我的代码:

<head>
    <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="typeahead.jquery.min.js"></script>
    <script src="bloodhound.min.js"></script>
</head>

<body>
<div id="prefetch">
<input class="typeahead" type="text" placeholder="Countries">
</div> 
<script>

var countries = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 4,
    prefetch: {
        url: 'countries.json',
    }
});

countries.clearPrefetchCache();
countries.initialize();

$('#prefetch .typeahead').typeahead(null, {
    name: 'countries',
    displayKey: 'country',
    source: countries.ttAdapter(),
}); 

</script>


</body>`

Json 文件 (countries.json):

[
    {
    "country": "Holland",
    "city": "Amsterdam"
    },
    {
    "country": "Belgium",
    "city": "Brussel"
    },
    {
    "country": "Germany",
    "city": "Berlin"
    },
    {
    "country": "France",
    "city": "Paris"
    }

]

您的 datumTokenizer 配置不正确。它应该是这样的。

datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country'),

这是一个demo

我知道这个问题很老了,但我希望这能有所帮助。

又一个简单的方法,对我有帮助,如果你的json是这样的...

var data = [
  {"stateCode": "CA", "stateName": "California"},
  {"stateCode": "AZ", "stateName": "Arizona"},
  {"stateCode": "NY", "stateName": "New York"},
  {"stateCode": "NV", "stateName": "Nevada"},
  {"stateCode": "OH", "stateName": "Ohio"}
];

$('#states').typeahead({
  name: 'states',
  limit: 10,
  minLength: 1,
  source: function (query, process) {
    states = [];
    map = {};
    $.each(data, function (i, state) {
        map[state.stateName] = state;
        states.push(state.stateName);
    });
    process(states);
  }
});