Jquery 提前输入更改源

Jquery 提前输入更改源,jquery,twitter-bootstrap,typeahead.js,typeahead,Jquery,Twitter Bootstrap,Typeahead.js,Typeahead,我正试图更改typeahead的来源,但我找到的所有答案都不适用于我(可能是因为更新的引导版本)。我根据用户搜索的内容进行了后端搜索。这是我的密码: $('.typeahead').typeahead({ hint: true, highlight: true, minLength: 1, limit: 2, }, { name: 'organizations', source: su

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

$('.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()方法:


如果我不能更新源代码,如何根据我键入的内容查找结果?提前谢谢

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

source: function(query, sync, async) { .. }
其中
sync
async
是回调。我猜您返回的JSON在表单上

[ 
  { "name" : "qwerty" },
  { "name" : "another qwerty" },
  ... 
]
在使用JSON时,定义一个
displayKey
,以便typeahead知道应该在下拉列表中显示哪个键/值属性,这一点很重要。所以

$('.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);
           })
        })
    }
});
上面将自动显示带有突出显示子字符串的typeahead。坚定地致力于

如果您想在typeahead中显示一些其他值,即前面提到的
val.coc_number+”、“+val.name
,则在调用
async()
之前,操作返回的JSON:

并相应更改
displayKey

displayKey: 'numberName', 

工作起来很有魅力!非常感谢!使用typeahead的源代码选项的一个工作示例也可以在这个答案中找到
data = data.map(function(item) { 
   item.numberName = item.coc_number + ", " + item.name;
   return item;
})
displayKey: 'numberName',