如何让typeahead JS使用我的json文件

H_C*_*H_C 5 typeahead bootstrap-typeahead

我想用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>`
Run Code Online (Sandbox Code Playgroud)

Json文件(countries.json):

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

]
Run Code Online (Sandbox Code Playgroud)

Dhi*_*raj 6

您的datumTokenizer配置不正确.它看起来应该是这样的.

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

这是一个演示

我知道这个问题很老但我希望这会有所帮助.


zar*_*pio 5

另一个简单的方法,它帮助了我,如果你的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);
  }
});
Run Code Online (Sandbox Code Playgroud)