简体   繁体   中英

How to display remote results with Twitter Typeahead?

I want to use Twitter Typeahead with a remote db datasource. I managed to get the results returned from my .php file with

return json_encode($results);

The are formatted like this:

["chrome","test01","test02","wddwde"].

But I do not know how to get them to show as suggestions?

For comparison I added the prefetched 'countries_bloodhound' as well as the integration part of this variable and it works fine. I need help with 'users_bloodhound' and its integration.


var users_bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    //name: 'users',
    remote: {url:'./search.php?query=%QUERY',
    wildcard: 'QUERY',
    transform: function(response) {
          // Map the remote source JSON array to a JavaScript object array
          return $.map(response.results, function(user) {
            return {
                name: user
            };
          }
      );}
      },
    limit: 10
});

var countries_bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'https://cdn.rawgit.com/twitter/typeahead.js/gh-pages/data/countries.json',
        filter: function (countries) {
            return $.map(countries, function (country) {
                return {
                    name: country
                };
            });
        }
    }
});


countries.initialize();
users_bloodhound.initialize();



$('#bloodhound .typeahead').typeahead({
  highlight: true
}, {
    name: 'users',
    displayKey: 'name',
    source: users_bloodhound.ttAdapter(),
    templates: {
        header: '<h4 class="search-name"><small>Users</small></h4>'
      }},{
        name: 'countries',
          displayKey: 'name',
          source: countries_bloodhound.ttAdapter(),
        templates: {
            header: '<h4 class="search-name"><small>Countries</small></h4>'
          }
});

The code is correct. I had some problems with my .php file because I returned the results instead of echoing them.

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