简体   繁体   中英

Twitter typeahead.js with remote array

I want to use twtter's typeahead to show some input suggestions. The suggestions will come from the server so I need to use the remote form: http://twitter.github.io/typeahead.js/examples/

But the remote examples are all returning json. Since I will have a quite big set of data and I want to store it in Redis I thought I would store the data not in json but in an array of values. To save memory.

I'm not yet on the Redis part, but simply trying to return a array. But I just get a bunch of undefined options to select from.

Any indications would be appreciated.

I'm on Rails. Assuming I would return render :text => ["abc", "sdf", "erw", gfg"] from the server, how could I make typeahead to display suggestions based on that response?

This is the example I would like to adapt to take an array instead of 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()
});

Thanks.

I'll answer myself

<script type="text/javascript">

$(function() {
      var xx = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace("user"),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: {
        url: '/home/cp?c=%QUERY',
         filter: function(list) {
            console.log(list)
            return $.map(list, function(name) { return { user: name}; });
        }
      } 
    });

    xx.initialize();

    $('#remote .typeahead').typeahead(null, {
      name: 'xx',
      displayKey: 'user',
      source: xx.ttAdapter()
    }); 


})


</script>



<div id="remote" style="text-align:center; margin-top: 200px;">
    <input class="typeahead" type="text">
</div>

So returning render json: %w[foo bar] from the controller will display the available options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM