Using Typeahead with Google Custom Search Engine

冷暖自知 提交于 2019-12-23 10:15:08

问题


I'm trying to get Twitter Typeahead+Bloodhound to work with Google's CSE.

So far, I've managed to get the results returning, but I'm not able to work out the 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
  }
});

See the fiddle: http://jsfiddle.net/thugsb/3KAjh/

You'll see that I've got the results being returned from showResults() as an array. However, the call to showResults() from the filter: doesn't seem to be doing anything, as removing that line has no effect. So I'm not quite sure what is going on.

Note the duffCallback is what I worked out to do from reading this question. If there's a better way to make this work I'm all ears!


回答1:


Firstly the datumTokenizer you were using was not quite right. You need to change it to:

datumTokenizer: function(data) {
 return Bloodhound.tokenizers.whitespace(data.value)
}

Note how the "whitespace" function is now referencing the "data" input parameter instead of "d" which you were using.

As for a a solution to your problem, see it working here (for example try searching for "athletics"):

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

The main problem with your code was in your remote URL (and this had me confused too!). The offending query string parameters are:

...&callback=showResults&duffCallback=?

"duffCallback=?" is not required as specifying "datatype:'jsonp'" in the ajax object automatically adds the callback details (i.e. "?callback=?") used by the jsonp request. Also the "callback=showResults" is not required as the filter method is implicitly called by the Bloodhound framework when a successful jsonp request is made.

I agree that it's not obvious on how remote calls should be made when using Typeahead.js. An example of a remote call where the ajax object is specified and some documentation would be useful on Typeahead.js website!



来源:https://stackoverflow.com/questions/23394245/using-typeahead-with-google-custom-search-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!