我正在尝试使用 bloodhound和 typeahead创建自动完成。数据正确返回,但在选项中显示为 undefined
我的代码是:
HTML:
<form class="typeahead" role="search">
<div class="form-group">
<input type="search" name="q" class="form-control search-input" placeholder="Search" autocomplete="off">
</div>
</form>
Javascript:
var engine = new Bloodhound({
remote: {
url: '{{ route('search') }}?query=%QUERY',
wildcard: '%QUERY'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace
});
$(".search-input").typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
source: engine.ttAdapter(),
// This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
name: 'profileList',
// the key from the array we want to display (name,slug...)
templates: {
empty: [
'<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function (data) {
var profile = [];
profile.push(data);
console.log(profile);
return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
}
}
});
当我 console.log(data)
我得到 2 个结果,如下所示:
Hello Molly
hello-molly-436057803095647
但值显示为 undefined
。后端返回的数据如下:
{"name":"Hello Molly","slug":"hello-molly-436057803095647"}
我想显示name
和slug
像这样:return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
作为建议。我怎样才能做到这一点?
最佳答案
对于其他遇到困难的人,我必须创建一个转换函数:
transform: function(response) {
return $.map(response, function (profile) {
return {
name: profile.name,
slug: profile.slug
}
});
},
映射出 json 响应。另外,如果您使用大量浏览器缓存,请清除缓存,因为这会阻止 JavaScript 更新。
完整代码:
var engine = new Bloodhound({
remote: {
url: '{{ route('search') }}?query=%QUERY',
wildcard: '%QUERY',
transform: function(response) {
return $.map(response, function (profile) {
return {
name: profile.name,
slug: profile.slug
}
});
},
},
datumTokenizer: Bloodhound.tokenizers.whitespace('name', 'slug'),
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$(".search-input").typeahead({
hint: true,
highlight: true,
minLength: 1,
displayKey: 'name',
}, {
source: engine.ttAdapter(),
// This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
name: 'profileList',
// the key from the array we want to display (name,id,email,etc...)
templates: {
empty: [
'<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function (data) {
return '<a href="' + data.slug + '" class="list-group-item">' + data.name + '</a>'
}
}
});
关于javascript - 如何在 Twitter typeahead/bloodhound 的建议中显示多个返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43066632/