不带猎犬的提前输入会返回多个错误

时间:2019-01-11 10:43:17

标签: javascript typeahead.js

在我的custom.js中,下面的代码有效:

var cities = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: '/api/search/city?city=%QUERY',
    wildcard: '%QUERY'
  }
});

$('.typeahead').typeahead(
{
    highlight: true
},
{
    name: 'cities',
    display: 'title',
    source: cities
});

但是我想删除猎犬,仍然使用远程功能。原因是minLength在使用Bloodhound时不起作用,此外,我不需要在远程查询返回的内容之外使用其他建议引擎。我发现已应用this snippet

$('.typeahead').typeahead({
    minLength: 3,
    highlight: true,
},
{
  name: 'cities',
  display: 'title',
  source: function(query, syncResults, asyncResults) {
    $.get('/api/search/city?city=' + query, function(data) {
      asyncResults(data);
    });
  }
})

但是,一旦我到达第3个及以上字符(在minLength中定义),控制台就会显示:

app.js:3166 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"ti
    at isArrayLike (app.js:3166)
    at Function.each (app.js:3028)
    at Object.each (typeahead.bundle.js:966)
    at Dataset.getSuggestionsFragment [as _getSuggestionsFragment] (typeahead.bundle.js:1662)
    at Dataset.renderSuggestions [as _renderSuggestions] (typeahead.bundle.js:1628)
    at Dataset.append [as _append] (typeahead.bundle.js:1620)
    at async (typeahead.bundle.js:1724)
    at Object.success (custom.js:200)
    at fire (app.js:5945)
    at Object.fireWith [as resolveWith] (app.js:6075)

我发现调试起来很困难,因为我不确定所显示的所有错误。是isArrayLike是导致所有后续错误的元凶吗?

更新

如果我使用console.log(data),它会按预期显示:

[
   {
      "title":"City1"
   },
   {
      "title":"City2"
   },
   {
      "title":"City3"
   },
   {
      "title":"City4"
   },
   {
      "title":"City5"
   }
]

这是预期的。

1 个答案:

答案 0 :(得分:0)

我发现data是一个字符串。解决问题的方法是将data替换为JSON.parse(data)