Javascript 使用jquery以编程方式触发typeahead事件

Javascript 使用jquery以编程方式触发typeahead事件,javascript,jquery,twitter-bootstrap,bootstrap-typeahead,Javascript,Jquery,Twitter Bootstrap,Bootstrap Typeahead,我正在使用引导和typeaheads。我可以使用以下方法为输入字段设置类型aheads: var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON']; $('#search-field').typeahead({source: subjects}); 但这是静态的。我想提供autosuggest功能,因此当用户键入字符/单词时,我获取用户键入的查询,并发出http请求以

我正在使用引导和typeaheads。我可以使用以下方法为输入字段设置类型aheads:

var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];
$('#search-field').typeahead({source: subjects});
但这是静态的。我想提供autosuggest功能,因此当用户键入字符/单词时,我获取用户键入的查询,并发出http请求以JSON格式获取建议。以下是我执行此操作的代码:

$('#search-field').on('keyup', function(){
// fetch the search query
var query = $(this).val();
// array containing suggestions
var suggestions=[];

$.getJSON('http://localhost:8983/solr/suggest/?q='+ query +'&wt=json&json.wrf=?', {

})
    .done(function(response){
        console.log(response);
        $.each(response.spellcheck.suggestions[1].suggestion, function(){
            // add the suggestions into the array
            suggestions.push(this);
        });

        // set the source for typeahead
        $('#search-field').typeahead({source: suggestions});
        // how to trigger the search field to show these suggestions now???
    });

如您所见,我获取建议,创建一个数组并设置typeahead的源。但建议不会显示,因为为此,必须输入一些内容,这样做将再次调用我的“keyup”事件处理程序:(!那么有没有办法解决这个问题,并在源代码注册后立即显示typeaheads???

请求的功能已经内置到typeahead库中,它允许源代码作为一个函数,如下所示

$('#search-field').typeahead({
    source: function(query, process){
        $.getJSON('http://localhost:8983/solr/suggest/?q='+ query +'&wt=json&json.wrf=?', {

        }).done(function(response){
            var suggestions=[];
            $.each(response.spellcheck.suggestions[1].suggestion, function(){
                // add the suggestions into the array
                suggestions.push(this);
            });

            process(suggestions)
        });
    }
});

所请求的功能已经内置到typeahead库中,它允许源代码是一个函数,如下所示

$('#search-field').typeahead({
    source: function(query, process){
        $.getJSON('http://localhost:8983/solr/suggest/?q='+ query +'&wt=json&json.wrf=?', {

        }).done(function(response){
            var suggestions=[];
            $.each(response.spellcheck.suggestions[1].suggestion, function(){
                // add the suggestions into the array
                suggestions.push(this);
            });

            process(suggestions)
        });
    }
});

如果您能为我提供一个指向此文档的链接,以便我能够探索更多选项,我将不胜感激。谢谢您的帮助。@stalin,这是传递给源函数的回调方法,必须使用动态源函数调用array@stalin我已经在我的回答中添加了文档的链接。你可以找到它再次在选项部分下阅读所有可用选项options@stalin您可以删除keyup handler如果您能为我提供一个指向此文档的链接,以便我可以探索更多选项,我将不胜感激。谢谢您的帮助。@斯大林,这是传递给源函数的回调方法,必须使用电子动力源array@stalin我已经在我的回答中添加了文档的链接。你可以在选项部分找到它,阅读所有可用的options@stalin您可以删除keyup处理程序