2014-10-18 149 views
4

我正在尝试使用typeahead来显示Google建议。Typeahead显示结果为undefined

AJAX调用工作正常,正常返回的数据:

之前执行恢复处理(数据); 数据包含以“w”开头的字符串数组。

数据= “沃尔玛”, “天气”, “富国银行”, “worldstarhiphop”, “沃尔格林”, “维基百科”, “白页”, “世界杯”, “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); 
      }); 
     } 
    }); 

回答

7

更新:

经过一番研究,我发现了一个回答我的问题,并会张贴在这里,如果有人需要它。

诀窍是 - “进程” 回调函数期望的结果的格式:

[{值: “字符串1”},{值: “字符串2”},{值: “STRING3”}]

而不仅仅是一串字符串。

$('.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); 
     }); 
    } 
}); 
+0

谢谢。键入文档中也有旧版本。 – user257980 2015-11-22 12:52:08

+0

我得到了同样的错误,我正在关注[this](http://twitter.github.io/typeahead.js/examples/#the-basics)示例。我的来源是substringMatcher(状态)和状态是一个数组。 – user4584963 2015-12-28 03:10:35

+0

https://gist.github.com/jharding/9458744#file-the-basics-html修复了破解的初始示例http://twitter.github.io/typeahead.js/examples/ – 2016-11-22 14:21:41