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

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

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

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

Typeahead.js 0.10.0版现在使用一个独立的组件,称为build议引擎来提供build议数据。 带Typeahead.js的build议引擎叫做Bloodhound 。

因此,您不能“定义远程,而不必定义数据集function”。

这是一个远程数据源的工作例子(我在查询TheMovieDb API,尝试search“外国人”例如)可以在这里find:

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() }); 

请注意filter函数如何让您从非平凡的JSON数据源中select要用作提前提示的内容。


更新Typeahead 0.11.1

对于那些使用更新版本的typeahead,可以在这里find一个基于原始问题的工作示例:

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

对于Typeahead 0.10.0,新版本(0.11.1)有以下区别:

  • “filter”function已被重命名为“变换”。
  • 不需要在Bloodhound对象上调用初始化,也不需要在将它分配给远程源时调用ttAdapter()。
  • 现在需要在远程选项散列中指定通配符(例如%QUERY)。

那么你可以做这样的事情:

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

来源: 使用Typeahead.js没有猎犬

如果您想使用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() });