用血猎犬远程建议预先输入
这是我的代码:
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 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 done @ 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 } } });
使用远程数据源的代码示例如下:
https://jsfiddle.net/ka0v6bg7/
尝试搜索以“data”或“string”开头的字符串(注意,查询“data”会花费更长的时间,因为它是一个远程数据源!)
我唯一改变的是远程数据源。
因此要检查的事项是:
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