Typeahead 更改源

Typeahead change source

我正在尝试更改 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() 来自示例,它仅适用于字符串数组并且不需要 - 搜索是在服务器端执行的。您也不必响应用户输入,这是预先输入的工作。要将远程 JSON 查询用作 source,语法为:

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

其中 syncasync 是回调。我猜你返回的 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);
           })
        })
    }
});

以上将自动显示带有突出显示子字符串的预输入。确认正在 latest release.

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

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

并相应地更改 displayKey :

displayKey: 'numberName',