jQuery Typeahead 和 Bloodhound - 如何获得 JSON 结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22730407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:03:34  来源:igfitidea点击:

Typeahead and Bloodhound - how to get JSON result

jqueryjsontypeahead.js

提问by user1049961

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

我有国家/地区的 json 列表:http: //vocab.nic.in/rest.php/country/json

And I'm trying to get country_id and country name with Bloodhound suggestion engine. O tried following code:

我正在尝试使用 Bloodhound 建议引擎获取 country_id 和国家/地区名称。O 尝试以下代码:

var countries = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country_name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: 'http://vocab.nic.in/rest.php/country/json',
        filter: function(response) {
            return response.countries;
        }
    }
});

$('#my-input').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        displayKey: 'value',
        source: countries.ttAdapter()
    });

Which doesn't work. How should I change the code to make this work?

哪个不起作用。我应该如何更改代码以使其正常工作?

采纳答案by Jens A. Koch

// 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

Typeahead 的输出

Notes:

笔记:

  • data on your server = "prefetch".
  • data from outside = "remote"
  • 您服务器上的数据 =“预取”。
  • 来自外部的数据 =“远程”

回答by Nelles

NOTE: if you do all this and it still is not working examine your data.json file (whatever you have named it)

注意:如果你做了所有这些但它仍然不起作用,请检查你的 data.json 文件(无论你给它起什么名字)

example of good format: https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json

良好格式的示例:https: //github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json

['data1','data2',.....]

['data1','data2',.....]

I was tripped up on out of place quote.

我被不合适的报价绊倒了。