Typeahead with bloodhound remote suggestions
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 }); } } |
它可以与本地建议一起使用,但由于某些原因它不适用于遥控器。
URL
为什么在预输入中没有显示来自远程的建议?
此功能收到远程建议后,我立即在控制台中收到此错误:
Uncaught TypeError: Cannot read property 'length' of undefined
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 done @
libs.js:9314 jQuery.ajaxTransport.options.send.callback @ libs.js:9718
更新1
我的远程数据由nodeJS服务器API返回:
1 2 3 4 | router.route('/suggestions') .get(function(req, res) { res.json([{value: 'data10'}, {value: 'data30'}, {value: 'data20'}, {value: 'data40'}, {value: 'data50'}]) }); |
更新2
我确定我从服务器收到了正确的答案,因为我在console.log中看到它:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 } } }); |
使用远程数据源的代码示例如下:
https://jsfiddle.net/ka0v6bg7/
尝试搜索以" data"或" string"开头的字符串(注意,查询" data"将花费更长的时间,因为它是远程数据源!)
我唯一更改的是远程数据源。
因此要检查的内容是:
1)您正确引用了预输入。尝试从此处引用它:
1 | https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js |
作为测试。
2)Jquery错误表明它可能未正确引用。同样,作为测试,请尝试从此处引用JQuery:
1 | https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js |