【问题标题】:How to use Bloodhound with a JSON created with flask jsonify如何将 Bloodhound 与使用烧瓶 jsonify 创建的 JSON 一起使用
【发布时间】:2020-10-13 17:18:49
【问题描述】:

我正在尝试使用 Bloodhound 预输入功能来搜索我的烧瓶应用程序上的数据库。

我跟着这里: Twiiter Typeahead Custom Templates - Getting Default Example Working

$(document).ready(function(){
 var playerList = [{
"name": "Calvin Ridley",
"team": "ATL",
"id": 14
  }, {
    "name": "Rob Gronkowski",
    "team": "TB",
    "id": 15
  }];

  var players = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: $.map(playerList, function(d) {
      return {
        value: d.name,
        // pass `playerList` to `suggestion`
        suggest: d
      }
    })
  });

  players.initialize();

  $("#custom-templates .typeahead").typeahead(null, {
    name: "best-pictures",
    display: "value",
    source: players.ttAdapter(),
    templates: {
      notFound: [
        "<div class=empty-message>",
        "Unable to find any players that match the current query",
        "</div>"
      ].join("\n"),
      suggestion: function(data) {
        // `data` : `suggest` property of object passed at `Bloodhound`
        return "<div><strong>" + data.suggest.name + "</strong>" 
               + ' (' + data.suggest.team + ')' + "</div>"
      }
    }
  });

}); 

这很好用,但我想做的是使用由使用 jsonify 创建的 json 定义的 playerList。

@app.route('/players')
def playerdic():
    res=Player.query.all()
    list_players=[r.as_dict() for r in res]
    return jsonify(list_players)

这会创建一个我认为与我在本地创建的相同的 json。 Image of json found in /players

我认为我需要使用预取,但我不确定如何将其链接到“/players”,同时仍然允许我使用将 d.name 传递给值并将 d 传递给建议的函数。

【问题讨论】:

    标签: json flask sqlalchemy typeahead bloodhound


    【解决方案1】:

    我在这里找到了答案.... Bloodhound / typeahead : using remote with simple strings

    具体使用预取部分:

    $(document).ready(function(){
      var players = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: "http://127.0.0.1:5000/players",
            filter: function(data){
                return $.map(data, function(item){
                    return {
                     value: item.name + ' (' + item.team + ')',
                     suggest: item
                    };
                });
            }
        }
      });
    

    虽然我不喜欢这样,但我需要将 URL 明确设置为“http://127.0.0.1:5000/players”。

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 1970-01-01
      • 2021-09-02
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多