Twitter的typeahead.js 0.11.1预取不工作

问题描述:

我试图预取整JSON数据库(55KB),使用它与typeahead.js 0.11.1。我在这一天挣扎了整整一天,我发现typeahead.js文档非常基本。Twitter的typeahead.js 0.11.1预取不工作

我的JSON看起来是这样的:

[{ 
    "id": 1, 
    "name": "Green" 
}, { 
    "id": 2, 
    "name": "Red" 
}, { 
    "id": 3, 
    "name": "Blue" 
}] 

和JavaScript:

$(function() { 

    var tagSuggestion = new Bloodhound({ 
     datumTokenizer: function(d) { 
      return Bloodhound.tokenizers.whitespace(d.name); 
     }, 
     queryTokenizer: Bloodhound.tokenizers.whitespace, 
     limit: 10, 
     prefetch: { 
      url: 'ajax.json-colors.php' 
     } 
    }); 

    $('.typeahead').typeahead({ 
     hint: true, 
     highlight: true, 
     minLength: 2 
    }, { 
     name: 'tagSuggestion', 
     displayKey: 'name', 
     source: tagSuggestion.ttAdapter() 
    }); 

}); 

我不知道我做错了什么,而是提前键入不带预取工作。

+0

您可能需要重命名您的JSON文件'ajax.json-colors.json',而不是'ajax.json-colors.php',并确保路径存在。检查是否有任何控制台错误。 –

+0

@ArathiSreekumar数据库应该是动态的,是没有问题的接收数据到JavaScript对象 – denoise

+0

所以你可以看到未来通过给前端的数据?预取确实会发出ajax请求? –

也许沿着此线的东西可能工作:

var tagSuggestion = new Bloodhound({ 
    datumTokenizer: function(d) { 
     return Bloodhound.tokenizers.whitespace(d.name); 
    }, 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    limit: 10, 
    prefetch: { 
     url: 'ajax.json-colors.php', 
     filter: function (data) { 
      //console.log(data.response) --> see if this is your data in example above 
      return $.map(data.response, function (tags) { 
       return { 
        name: tags.name 
       }; 
      }); 
     } 
    } 
}); 

这是假设回来在预取的数据是,在有数据的响应对象的形式。可能需要根据什么data进行修改,将其传递给过滤器。

这是如果Ajax响应是键为“响应”的密钥值。没有工作小提琴,我只能猜测问题。

var tagSuggestion = new Bloodhound({ 
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), 
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    remote: { 
     url: 'ajax.json-colors.php?query=%QUERY', 
     wildcard: '%QUERY' 
    } 
}); 

$('.typeahead').typeahead({ 
    minLength: 2, 
    highlight: true 
}, 
{ 
    name: 'search', 
    display: 'value', 
    source: tagSuggestion 
}); 

似乎预输入不与PHP文件为预取源工作,并且只接受JSON文本文件:

finaly的问题是使用远程功能,改变了我的代码如下解决。