将Typeahead与Google自定义搜索引擎结合使用

thu*_*gsb 6 jquery jsonp google-custom-search typeahead.js bloodhound

我正试图让Twitter Typeahead + Bloodhound与Google的CSE合作.

到目前为止,我已经设法返回结果,但我无法计算出datumTokenizer.

var results = new Bloodhound({
  datumTokenizer: function(data) {
   return Bloodhound.tokenizers.whitespace(d.value)
  },
  queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
  remote: {
    url: "http://clients1.google.com/complete/search?client=partner&hl=en&sugexp=gsnos%2Cn%3D13&gs_rn=25&gs_ri=partner&partnerid=004914516364918182382%3Ayfqw09r4qvu&types=t&ds=cse&cp=3&gs_id=15&q=%QUERY&callback=showResults&duffCallback=?",
    ajax: $.ajax({type:'GET',dataType:'jsonp',jsonp:'duffCallback'}),
    filter: showResults
  }
});
Run Code Online (Sandbox Code Playgroud)

看小提琴:http://jsfiddle.net/thugsb/3KAjh/

你会看到我将showResults()作为一个数组返回结果.但是,从中调用showResults()filter:似乎没有做任何事情,因为删除该行没有任何效果.所以我不太确定发生了什么.

请注意,duffCallback是我在阅读这个问题时要做的.如果有更好的方法来完成这项工作,我会全都耳朵!

Ben*_*ith 7

首先,您使用的datumTokenizer并不完全正确.您需要将其更改为:

datumTokenizer: function(data) {
 return Bloodhound.tokenizers.whitespace(data.value)
}
Run Code Online (Sandbox Code Playgroud)

请注意"空白"功能现在如何引用"数据"输入参数而不是您正在使用的"d".

至于你的问题的解决方案,看到它在这里工作(例如尝试搜索"田径"):

http://jsfiddle.net/Fresh/FYavC/

您的代码的主要问题在于您的远程URL(这让我感到困惑!).违规查询字符串参数是:

...&callback=showResults&duffCallback=?
Run Code Online (Sandbox Code Playgroud)

"duffCallback =?" 不需要,因为在ajax对象中指定" datatype:'jsonp' "会自动添加jsonp请求使用的回调详细信息(即"?callback =?").此外,不需要"callback = showResults",因为当成功的jsonp请求发出时,Bloodhound框架会隐式调用过滤器方法.

我同意在使用Typeahead.js时应该如何进行远程调用并不明显.远程调用的一个示例,其中指定了ajax对象,并且某些文档在Typeahead.js网站上很有用!