我正在使用bootstrap并使用typeaheads。我可以使用以下方法为输入字段设置输出类型:
var subjects = ['PHP', 'MySQL', 'SQL', 'PostgreSQL', 'HTML', 'CSS', 'HTML5', 'CSS3', 'JSON'];
$('#search-field').typeahead({source: subjects});
但这是静态的。我想提供自动提示功能,因此当用户键入字符/单词时,我获取用户键入的查询并发出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'事件处理程序:(!那么有没有办法解决这个问题并在源注册后立即显示输出内容为了它??
答案 0 :(得分:3)
请求的功能已内置到预先输入库中,它允许源是一个函数,如下面给出的documentation
$('#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)
});
}
});