在typeahead.js中使用prefetch而不是local时出现问题

时间:2014-04-08 19:51:10

标签: jquery local typeahead.js typeahead prefetch

我的代码可以正常使用本地数据,但如果我将本地数据复制到json文件并使用prefetch选项它不起作用,它只返回一个未定义的列表。

我想使用预取数据并收听自定义事件句柄typeahead:选中以填充多个输入字段。有什么建议可以解决这个问题吗?感谢。

我的代码在这里:

  <form>
<input type="text" class="typeahead" id="subject_label" /><br/>
<input type="text"  id="subject_id" /><br/>
</form>
var s = [{"id":"1234","label":"fish"},{"id":"5678","label":"histo"}]

var labels = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.label);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    //  local option is working  
    //  local: s
    // If using prefetch url option with exactly same dataset, the code is broken, I'm  
    //sure the url format is correct.
     prefetch: '/sample.json'

});

labels.initialize();

var subjectLabelTypeahead = $('#subject_label.typeahead');
var subjectIdTypeahead = $('#subject_id');

// Initialise typeahead 
subjectLabelTypeahead.typeahead({
    highlight: true
}, {
    name: 'label',
    displayKey: 'label',
    source: labels.ttAdapter()
});

// Set-up event handlers so that the ID is auto-populated when select label 
var subjectLabelItemSelectedHandler = function (e, datum) {
    subjectIdTypeahead.val(datum.id);
};

subjectLabelTypeahead.on('typeahead:selected', subjectLabelItemSelectedHandler);

1 个答案:

答案 0 :(得分:0)

您的&#34;预取&#34; value应引用javascript对象而不是URL字符串(请参阅文档here)。

尝试将其更改为:

var labels = new Bloodhound({
 datumTokenizer: function (d) {
    return Bloodhound.tokenizers.whitespace(d.label);
 },
 queryTokenizer: Bloodhound.tokenizers.whitespace,
 prefetch: {
  url: '/sample.json',
  filter: function(items) {
   return $.map(items, function(item) { 
    return { 
     label: item.label,
     id: item.id }; 
   });
  }
});
相关问题