从jQuery自动完成切换到Twitter Typeahead

时间:2014-10-02 11:54:26

标签: jquery typeahead.js

我有一些使用autocomplete jquery插件的代码,源代码是动态生成的json文件。

funderInput.autocomplete({
    //Look up funders by name and show suggestions
    source:function(request, response) {
        $.getJSON("/funder/suggest?name=" + request.term, function(data){
            response($.map(data.result.suggestions, function(item, index) {
                return {label: item.name + " (" + item.location + ")", value: item.fundref};
            }))
        })
    }
});

我无法弄清楚如何在Typeahead中做类似的事情。 文档中的示例提供了以下内容,但似乎使用静态JSON文件。

var bestPictures = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: '../data/films/post_1960.json',
  remote: '../data/films/queries/%QUERY.json'
});

bestPictures.initialize();

$('#remote .typeahead').typeahead(null, {
  name: 'best-pictures',
  displayKey: 'value',
  source: bestPictures.ttAdapter()
});

我试过这个,但并没有真正走得太远!

defaults.typeahead.typeahead({
    // Options
    minLength: 1,
    highlight: true,
}, {
    // Dataset
    source: function (query, process) {
        $.getJSON("/funder/suggest?name=" + query, function (data) {
            response($.map(data.result.suggestions, function (item, index) {
                return {
                    label: item.name + " (" + item.location + ")",
                    value: item.fundref
                };
            }))
        });
    }
});

我是一名JavaScript新手,所以如果可能的话,我正朝着正确的方向轻轻一搏。

1 个答案:

答案 0 :(得分:1)

typeahead函数中的

称为进程而不是响应。尝试返回流程

source: function (query, process) {
        $.getJSON("/funder/suggest?name=" + query, function (data) {
           return  process($.map(data.result.suggestions, function (item, index) {
                return {
                    label: item.name + " (" + item.location + ")",
                    value: item.fundref
                };
            }))
        });
    }