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

时间:2015-03-18 10:52:10

标签: typeahead bootstrap-typeahead

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

这是我的代码:

<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"
    }

]

2 个答案:

答案 0 :(得分:5)

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

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

这是demo

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

答案 1 :(得分: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);
  }
});