【发布时间】:2015-09-12 05:14:44
【问题描述】:
我正在尝试使用typeahead.js 在表单中显示 ajax 结果。
起初我尝试使用Bloodhound 建议引擎,它默认带有typeahead。但它没有显示服务器返回的所有项目(我只显示 1 个或有时两个)。
以下是我使用的代码;
$('.autocomplete').livequery(function () {
var input = this;
$(input).removeClass('autocomplete');
var _source = new Bloodhound({
limit: 25,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.obj.whitespace('Text'),
prefetch: $(input).attr('data-source'),
remote: {
url: $(input).attr('data-source') + '?query=%QUERY',
wildcard: '%QUERY'
}
});
_source.initialize();
$(input).typeahead({
hint: true,
highlight: true,
minLength: 0
}, {
displayKey: 'Text',
source: _source,
templates: {
notFound: 'No results found'
}
});
$(input).on('typeahead:selected', function (evt, item) {
$(input).parent().parent().find('input[type="hidden"]').val(item.Value);
});
})
然后我尝试在没有 Bloodhound 的情况下使用以下代码执行此操作,结果没有任何变化;
$('.autocomplete').livequery(function () {
var input = this;
$(input).removeClass('autocomplete');
$(input).typeahead({
hint: true,
highlight: true,
limit: 50,
minLength: 0
}, {
displayKey: 'Text',
source: function (query, syncResults, asyncResults) {
$.get($(input).attr('data-source') + '?query=' + query, function (data) {
asyncResults(data);
});
},
templates: {
notFound: 'No results found'
}
});
$(input).on('typeahead:selected', function (evt, item) {
$(input).parent().parent().find('input[type="hidden"]').val(item.Value);
});
})
服务器对请求的响应如下;
[
{
"Text": "Marketing Executive",
"Value": 1
},
{
"Text": "CEO",
"Value": 5
},
{
"Text": "Manager",
"Value": 6
},
{
"Text": "Accountant",
"Value": 7
}]
这有什么问题?以及如何提前输入以显示服务器返回的所有结果?
【问题讨论】:
-
默认只显示5条建议,使用
limit选项增加。检查docs -
@JSantosh
limit: 50,检查问题。 -
你看不到 50 个结果对吧?
-
@JSantosh 我在某处读到 typeahead 在同步结果较少时显示所有异步结果存在一些问题。设置更高的限制是在 Internet 上找到的一种解决方法。
标签: javascript jquery typeahead.js bootstrap-typeahead