这是我的代码:
tagsProcessor(){
const suggestions = [{value: 'string1'}, {value: 'string2'}, {value: 'string3'}, {value: 'string4'}, {value: 'string5'}]
var bloodhoundSuggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
sufficient: 3,
local: suggestions,
remote: {
url: 'http://localhost:3001/api/suggestions',
}
});
const $tagsInput = $('#tagsInput')
$tagsInput.typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'suggestions',
displayKey: 'value',
source: bloodhoundSuggestions
});
}
}
它适用于本地建议,但由于某种原因它不适用于遥控器。
网址http://localhost:3001/api/suggestions
返回一个对象数组,与suggestions
常量类似。
为什么没有来自遥控器的建议显示在预先输入中?
我在此功能收到远程建议后立即在控制台中收到此错误:
未捕获的TypeError:无法读取未定义的属性“length” jQuery.extend.each @ libs.js:358 _.each @ libs.js:17928 processRemote @ libs.js:18763 onResponse @ libs.js:18515 done @ libs.js:18254 jQuery.Callbacks.fire @ libs.js:3148 jQuery.Callbacks.self.fireWith @ libs.js:3260完成@ libs.js:9314 jQuery.ajaxTransport.options.send.callback @ libs.js:9718
更新1 我的远程数据由nodeJS服务器API返回:
router.route('/suggestions')
.get(function(req, res) {
res.json([{value: 'data10'}, {value: 'data30'}, {value: 'data20'}, {value: 'data40'}, {value: 'data50'}])
});
更新2 我确定我从服务器收到了正确的答案,因为我在console.log中看到了它:
var bloodhoundSuggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: suggestions,
remote: {
url: 'http://localhost:3001/api/suggestions',
transform: function(argument) {
console.log('argument', argument)
return argument
}
}
});
答案 0 :(得分:5)
使用远程数据源的代码示例如下:
https://jsfiddle.net/ka0v6bg7/
尝试搜索以&#34开头的字符串;数据"或"字符串" (注意,查询"数据"因为它是一个远程数据源会花费更长的时间!)
我唯一改变的是远程数据源。
因此要检查的事项是:
1)您正确引用了typeahead。尝试从这里引用它:
https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js
作为测试。
2)Jquery错误表明它可能没有被正确引用。同样,作为测试尝试从这里引用JQuery:
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js