我一直在使用Spring MVC应用程序并试图使用Twitter Typeahead来显示建议。但问题是虽然建议是从服务器正确获取的,但建议框根本没有显示。相同的代码以前有效但现在不能正常工作。
我的javascript代码是:
var skillSuggestions=new Bloodhound({
datumTokenizer:Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer:Bloodhound.tokenizers.whitespace,
remote:{
url:"/tags/get.html/?searchTerm=%QUERY",
filter:function(x){
return $.map(x,function(item){
return{value:item.name};
});
},
wildcard:'%QUERY',
}
});
skillSuggestions.initialize();
$('#skill-name').typeahead({
hint:true,
highlight:true,
minLength:1
},{
name:'value',
displayKey:'value',
source:skillSuggestions.ttAdapter()
})
并输入' j'收到的json回复是:
[{"id":"56d546f5535a3c819f080558","name":"Java","category":"Information Technology","subCategory":"Programming/Software","createdDate":1456817909648,"updatedDate":null,"createdBy":"bob","modifiedBy":null},{"id":"56d93f8e535a773c1f8cc846","name":"Javascript","category":"Information Technology","subCategory":"Programming / Software","createdDate":1457078158043,"updatedDate":null,"createdBy":"bob","modifiedBy":null},{"id":"56d93fa2535a773c1f8cc847","name":"JQuery","category":"Information Technology","subCategory":"Programming / Software","createdDate":1457078178030,"updatedDate":null,"createdBy":"bob","modifiedBy":null},{"id":"56d93fb7535a773c1f8cc848","name":"JavaSE","category":"Information Technology","subCategory":"Programming / Software","createdDate":1457078199012,"updatedDate":null,"createdBy":"bob","modifiedBy":null},{"id":"56e226a47b49d4215eaefa9a","name":"javahhhh","category":"hhhhh","subCategory":"jjjjjj","createdDate":1457661604324,"updatedDate":null,"createdBy":null,"modifiedBy":null}]
答案 0 :(得分:4)
问题在于您的基准标记器。您在响应对象中的密钥value
中进行了标记,但您的响应中不存在该密钥。 obj.whitespace
标记生成器接受标记化的对象键列表。
改变这个:
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("Value"),
到此(例如):
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name", "category"),
更改标记生成器时,还需要更改显示为建议的内容和所选选项。您尝试在typeahead选项中使用此行执行此操作:
displayKey:'value',
...但是,您再次引用了不存在的对象键(value
)。您需要密钥name
。
display: 'name', // This is the object key you wish displayed
答案 1 :(得分:0)
我会告诉你我是如何在我们的实现中解决它的。我们在数据上使用identify
函数和filter
函数。
在这种情况下,通过Web服务返回的数据具有id
属性和name
属性。这些映射到用于填充实际预先建议的对象。
taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("Value"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function (obj) { return obj.Value; },
remote: {
url: "/service/url",
filter: function (data) {
if (data) {
return $.map(data, function (object) {
return { Id: object.id, Value: object.name };
});
} else {
return {};
}
},
rateLimitBy: 'debounce',
rateLimitWait: 400
}
});
请注意,我映射了Id属性和Value属性。检查你的案件的房产名称。