我们如何在Typeahead.js中设置远程?

时间:2014-02-03 14:35:40

标签: javascript autocomplete remote-server typeahead typeahead.js

在以前的版本中,我可以这样做:

$('#search').typeahead({
  name: 'Search',
  remote: '/search?query=%QUERY'
});

但是自0.10更新以来,typeahead.js要求我们定义source,我无法使其工作。如何定义远程而无需定义数据集函数?

3 个答案:

答案 0 :(得分:96)

Typeahead.js版本0.10.0现在使用一个名为建议引擎的独立组件来提供建议数据。 Typeahead.js附带的建议引擎称为Bloodhound

因此,您无法“定义远程而无需定义数据集函数”。

使用远程数据源(我正在查询TheMovieDb API,尝试搜索“Aliens”)的示例可在此处找到:

http://jsfiddle.net/Fresh/UkB7u/

代码在这里:

// Instantiate the Bloodhound suggestion engine
var movies = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'http://api.themoviedb.org/3/search/movie?query=%QUERY&api_key=470fd2ec8853e25d2f8d86f685d2270e',
        filter: function (movies) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(movies.results, function (movie) {
                return {
                    value: movie.original_title
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
movies.initialize();

// Instantiate the Typeahead UI
$('.typeahead').typeahead(null, {
    // Use 'value' as the displayKey because the filter function 
    // returns suggestions in a javascript object with a variable called 'value'
    displayKey: 'value',
    source: movies.ttAdapter()
});

请注意过滤器功能如何允许您从非平凡的JSON数据源中选择要用作预先输入建议的内容。


Typeahead 0.11.1

的更新

对于那些使用较新版本的typeahead的用户,可以在此处找到基于原始问题的工作示例:

http://jsfiddle.net/Fresh/bbzt9hcr/

对于Typeahead 0.10.0,新版本(0.11.1)有以下不同之处:

  • “过滤器”功能已重命名为“transform”。
  • 无需在Bloodhound对象上调用initialize,也不需要在将其分配给远程源时调用ttAdapter()。
  • 现在需要在远程选项哈希中指定通配符(例如%QUERY)。

答案 1 :(得分:21)

你可以这样做:

$('input#keywords').typeahead({
    highlight: true,
},
{
  name: 'brands',
  display: 'value',
  source: function(query, syncResults, asyncResults) {
    $.get('/search?q=' + query, function(data) {
      asyncResults(data);
    });
  }
})

来源:Using Typeahead.js without Bloodhound

答案 2 :(得分:8)

如果你想使用ajax POST数据而不是GET数据来进行更多受控的ajax调用,你可以使用这个结构:

var meslekler = new Bloodhound({
    datumTokenizer: function (d) {
            return Bloodhound.tokenizers.whitespace(d.isim);
        },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'my_url_with_or_without_%query_token.php',
        ajax:{
            type:"POST",
            cache:false,
            data:{
                limit:5
            },
            beforeSend:function(jqXHR,settings){
                settings.data+="&q="+$('.tt-input').typeahead('val');
            },
            complete:function(jqXHR,textStatus){
            meslekler.clearRemoteCache();
            }
        }
    }
});
meslekler.initialize();
$('.typeahead').typeahead(null, {
    name:'meslekler',
    displayKey: 'isim',
    source: meslekler.ttAdapter()
});
相关问题