简体   繁体   English

在Json中使用typeahead.js

[英]Using typeahead.js with Json

I'm following this link which is a great clear blog post about typeahead.js with Json. 我正在关注此链接该链接是有关Json的typeahead.js的出色清晰博客文章。 However, I'm having problems with it and can't figure out where I'm going wrong. 但是,我遇到了问题,无法弄清楚我要去哪里。

Here is my js: 这是我的js:

<script type="text/javascript">
    $('#Search').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        displayKey: 'stateName',
        source: function (query, process) {
            states = [];
            map = {};

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

            $.each(data, function (i, state) {
                map[state.stateName] = state;
                states.push(state.stateName);
            });

            process(states);
        },
        updater: function (item) {
            selectedState = map[item].stateCode;
            return item;
        }
    });
</script>

When I type in the input control all the results come back as undefined. 当我输入输入控件时,所有结果都将返回未定义状态。 I think it's something to do with the displayKey and I've tried setting it to state.stateName but that results in the same problem. 我认为这与displayKey有关,我尝试将其设置为state.stateName,但这会导致相同的问题。 Maybe I'm looking in the wrong area? 也许我在找错地方了?

I've setup a plnkr.co demo here. 我在这里设置了plnkr.co演示。

Thanks for reading. 谢谢阅读。

Paul 保罗

You need to change your states.push row, in your plunker it is on row 45. Typeahead expects results in JSON format, now you are just pushing results. 您需要更改states.push行,在pluker中的第45行。Typeahead期望结果为JSON格式,现在您只是在推送结果。

Change row 45 to: 将第45行更改为:

states.push({stateName : state.stateName});

Now your displayKey: "stateName" (which is the key of JSON formatted data) will exist and it will show the name of the state as a result. 现在,您的displayKey:“ stateName”(这是JSON格式的数据的键)将存在,并且将显示状态的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM