Typeahead and Bloodhound - how to get JSON result

前端 未结 2 476
天命终不由人
天命终不由人 2020-12-29 07:29

I have the json list of Countries: http://vocab.nic.in/rest.php/country/json

And I\'m trying to get country_id and country name with Bloodhound suggestion engine. O

2条回答
  •  孤独总比滥情好
    2020-12-29 08:00

    // instantiate the bloodhound suggestion engine
    var countries = new Bloodhound({  
      datumTokenizer: function(countries) {
          return Bloodhound.tokenizers.whitespace(countries.value);
      },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: {
        url: "http://vocab.nic.in/rest.php/country/json",
        filter: function(response) {      
          return response.countries;
        }
      }
    });
    
    // initialize the bloodhound suggestion engine
    countries.initialize();
    
    // instantiate the typeahead UI
    $('.typeahead').typeahead(
      { hint: true,
        highlight: true,
        minLength: 1
      }, 
      {
      name: 'countries',
      displayKey: function(countries) {
        return countries.country.country_name;        
      },
      source: countries.ttAdapter()
    });
    

    Example Codepen

    Typeahead Output

    Output of Typeahead

    Notes:

    • data on your server = "prefetch".
    • data from outside = "remote"

提交回复
热议问题