Typeahead v0.10.2 和 Bloodhound - 使用嵌套 JSON 对象

2023-12-30

UPDATE

基于@BenSmith 的正确答案(https://stackoverflow.com/users/203371/BenSmith https://stackoverflow.com/users/203371/BenSmith)我能够找到我的问题,并发现我没有正确浏览我的 JSON 层次结构。这是工作代码:

        // instantiate the bloodhound suggestion engine
    var engine = new Bloodhound({
        datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.title);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: "SampleData.json",
            filter: function (data) {
                //console.log("data", data.response.songs)
                return $.map(data.response.songs, function (song) {
                    return {
                        title: song.title,
                        artistName: song.artist_name
                    };
                });
            }
        }
    });

    // initialize the bloodhound suggestion engine
    engine.initialize();

    // instantiate the typeahead UI
    $('#prefetch .typeahead').typeahead(
      {
          hint: true,
          highlight: true,
          minLength: 1
      },
      {
          name: 'engine',
          displayKey: 'title',
          source: engine.ttAdapter(),
          templates: {
              empty: [
              '<div class="empty-message">',
              'unable to find any results that match the current query',
              '</div>'
              ].join('\n'),
              suggestion: Handlebars.compile('<p><strong>{{title}}</strong> by {{artistName}}</p>')
          }
      });

感谢@BenSmith 的帮助!


原始问题

我是使用 Typeahead 和 Bloodhound 的新手。该文档不是很有帮助。我有一组 JSON 对象,是从我正在使用的 API 中获取的。我试图弄清楚如何浏览我的 JSON 对象,以便 Bloodhound 可以理解它们。

这里的目标是用户开始输入歌曲名称。然后,自动完成功能将显示歌曲名称及其表演者的列表。

例如:Mastodon 的午夜钟声

我正在使用每个库的最新版本:https://twitter.github.io/typeahead.js/ https://twitter.github.io/typeahead.js/

示例 JSON (SampleData.json):



{"response": {"status": {"version": "4.2", "code": 0, "message": "Success"}, "songs": [{"title": "Chimes At Midnight", "artist_name": "Mastodon", "artist_foreign_ids": [{"catalog": "7digital-AU", "foreign_id": "7digital-AU:artist:29785"}, {"catalog": "7digital-UK", "foreign_id": "7digital-UK:artist:29785"}], "tracks": [], "artist_id": "ARMQHX71187B9890D3", "id": "SOKSFNN1463B7E4B1E"}, {"title": "Down Under", "artist_name": "Men at Work", "artist_foreign_ids": [{"catalog": "7digital-AU", "foreign_id": "7digital-AU:artist:50611"}], "tracks": [], "artist_id": "AR4MVC71187B9AEAB3", "id": "SORNNEB133A920BF86"}]}}
  

使用这个网站http://json.parser.online.fr/ http://json.parser.online.fr/轻松格式化 JSON。

我将返回的 JSON 将始终采用相同的格式,但包含不同的数据。在此示例中,“轨道”为空。其他结果会有数据。我还需要能够访问这些数据。

我正在使用最新版本的 JQuery。这是我在 html 页面中包含的内容:

<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/typeahead.bundle.min.js"></script>

这是 HTML:

<div id="prefetch">
    <input class="typeahead" type="text" placeholder="Songs...">
</div>

这是脚本:

    // instantiate the bloodhound suggestion engine
    var engine = new Bloodhound({
        datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.tokens.join(' ')); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: "SampleData.json",
            filter: function (response) {
                return response.engine;
            }
        }
    });

    // initialize the bloodhound suggestion engine
    engine.initialize();

    // instantiate the typeahead UI
    $('#prefetch .typeahead').typeahead(
      {
          hint: true,
          highlight: true,
          minLength: 1
      },
      {
          name: 'songs',
          displayKey: function (engine) {
              return engine.songs.artist_name;
          },
          source: engine.ttAdapter()
      });

当我尝试运行此代码时,出现以下错误:

未捕获的类型错误:无法读取未定义的属性“令牌”

此处的任何帮助或指导将不胜感激。我只需要知道如何获取我正在使用 Typeahead/Bloodhound 处理的 JSON 数据。

Thanks!


您需要编写过滤器函数,以便它创建一个 javascript 对象数组来用作数据。以下应该有效(我没有测试过):

filter: function (response) {
            return $.map(response.songs, function (song) {
                return {
                    title: song.title,
                    artistName: song.artist_name
                };
            });
        }

(过滤功能的例子可以找到here http://jsfiddle.net/Fresh/UkB7u/)

并将您的 datumtokenizer 更改为:

datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.title);
    }

还将您的显示键更改为:

displayKey: 'title'

因为这是 Typeahead 将用于搜索的键。

至于在建议列表中显示歌曲名称和艺术家,我建议您使用模板(例如 Handlebars)来显示结果。请参阅“自定义模板”示例Typeahead 的示例页面 http://twitter.github.io/typeahead.js/examples/。您的建议标记将类似于以下内容:

suggestion: Handlebars.compile('<p><strong>{{title}}</strong> by {{artistName}}</p>')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typeahead v0.10.2 和 Bloodhound - 使用嵌套 JSON 对象 的相关文章

随机推荐