Typeahead更改源

我正在尝试更改typeahead的来源,但是我找到的所有答案都不适用于我(可能是因为更新的bootstrap版本)。 我根据用户搜索的内容进行了后端搜索。 这是我的代码:

$('.typeahead').typeahead({ hint: true, highlight: true, minLength: 1, limit: 2, }, { name: 'organizations', source: substringMatcher(getOrganizationData()) }).on("input", function(e) { organizationQuery = e.target.value; // Here I want to update the source // Not working: //$(".typeahead").data('typeahead').source = substringMatcher(getOrganizationData()) // Not working: //$('.typeahead').data('ttTypeahead').dropdown.datasets[0].source = substringMatcher(getOrganizationData()) // Not working: // var autocomplete = $('input').typeahead(); // autocomplete.data('typeahead').source = substringMatcher(getOrganizationData()); }); 

这是我的getOrganizationData()方法:

 function getOrganizationData() { var tempResults = []; $.getJSON( "search-organization?query="+organizationQuery, function( data ) { $.each(data, function (key, val) { var display = val.coc_number + ", " + val.name tempResults[key] = display; organizationHolder[display] = val.id; }); }); return tempResults; } 

如果我无法更新源代码,我应该如何找到基于我输入内容的结果? 提前致谢!

AFAIK substringMatcher()来自示例,它仅适用于字符串数组而不需要 – 搜索是在服务器端执行的。 此外,您不必响应用户输入,即typeaheads作业。 要使用远程JSON查询作为source ,语法为:

 source: function(query, sync, async) { .. } 

其中syncasync是回调。 我猜你的返回JSON在表单上

 [ { "name" : "qwerty" }, { "name" : "another qwerty" }, ... ] 

使用JSON时,定义displayKey很重要,因此displayKey知道它应该在下拉列表中显示哪个键/值属性。 所以

 $('.typeahead').typeahead( { hint: true, highlight: true, minLength: 1, limit: 2, },{ name: 'organizations', displayKey: 'name', //example source: function(query, sync, async) { $.getJSON( "search-organization?query="+query, function( data ) { async(data); }) }) } }); 

以上将自动显示带有突出显示的子串的预先输入。 确认正在处理最新版本 。

如果要在val.coc_number + ", " + val.name显示一些其他值,即提到的val.coc_number + ", " + val.name则在调用async()之前操作返回的JSON:

 data = data.map(function(item) { item.numberName = item.coc_number + ", " + item.name; return item; }) 

并相应地更改displayKey

 displayKey: 'numberName',