Typeahead将结果显示为undefined

时间:2014-10-18 16:33:35

标签: javascript typeahead bootstrap-typeahead

我正在尝试使用typeahead来显示Google建议。

Ajax调用正常,数据正确返回:

在执行返回流程(数据); 之前 data包含以“w”开头的字符串数组。

  

data = [“walmart”,“weather”,“well fargo”,“worldstarhiphop”,   “walgreens”,“维基百科”,“白页”,“世界杯”,“webmd”,   “天气雷达”]

然而,显示的建议显示“未定义”而不是真实的单词。 知道我在这里缺少什么吗?感谢。

enter image description here

    <input type="text" class="typeahead" placeholder="Search">


    $('.typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        source: function (query, process) {
            $.getJSON("Home/Suggest", { query: query }, function (data) {
                return process(data);
            });
        }
    });

1 个答案:

答案 0 :(得分:8)

更新

经过一些研究,我找到了我的问题的答案,如果有人需要,我会在这里发布。

诀窍是 - &#34;过程&#34;回调函数期望结果格式为:

[{value:&#34; string1&#34;},{value:&#34; string2&#34;},{value:&#34; string3&#34;}]

而不只是一个字符串数组。

$('.typeahead').typeahead(
{ hint: true, highlight: true, minLength: 1 }, // options
{
    source: function (query, process) { // source dataset, data = array of strings
        $.getJSON('Home/Suggest', { query: query }, function (data) {
            //data=["string1", "string2", "string3"]
            //process callback function needs it 
            //in a format [{value: "string1"}, {value: "string2"}, {value: "string3"}]
            var output = $.map(data, function (string) { return { value: string }; });
            process(output);
        });
    }
});