这是我的代码:

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完成@ 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
        }
  }
});

最佳答案

您的代码使用远程数据源的示例如下:

https://jsfiddle.net/ka0v6bg7/

尝试搜索以“ data”或“ string”开头的字符串(注意,查询“ data”将花费更长的时间,因为它是远程数据源!)

我唯一更改的是远程数据源。

因此,要检查的事情是:

1)您正确引用了预输入。尝试从此处引用它:

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

10-04 22:11
查看更多