【问题标题】:Autocomplete search box and pass value to flask自动完成搜索框并将值传递给烧瓶
【发布时间】:2016-09-21 10:56:36
【问题描述】:

我正在准备一个演示,这是我第一次做“网络开发”。 所以,这可能完全是一个菜鸟问题,但这是我想要做的。

我想要两个在键入时自动完成的搜索框。

First search box: name
Second search box: song

我有两个文件names.txt和songs.txt

所以,这个想法是,当用户输入名称时,它会从 names.txt 中读取以生成自动完成,当用户输入歌曲时,搜索框会根据 song.txt 自动完成

然后将这些值传递给后端的烧瓶应用程序..

@app.route('/search', method=['post'])
def process():
  return name, song, and list of other songs with score (list a table)

我需要一个非常简单的例子(没什么花哨的),它就是这样做的..

谢谢

【问题讨论】:

  • 你有自动发布的自动完成框吗?您只需要帮助构建烧瓶 api 来返回数据吗?
  • @GMarsh no.. 我也需要 Javascript 部分

标签: javascript jquery html flask


【解决方案1】:

如何使用 jQuery-Autocomplete。这应该可以帮助您开始:

**/app.py**

from flask import Flask, request, render_template, jsonify
app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/search/<string:box>")
def process(box):
    query = request.args.get('query')
    if box == 'names':
        # do some stuff to open your names text file
        # do some other stuff to filter
        # put suggestions in this format...
        suggestions = [{'value': 'joe','data': 'joe'}, {'value': 'jim','data': 'jim'}]
    if box == 'songs':
        # do some stuff to open your songs text file
        # do some other stuff to filter
        # put suggestions in this format...
        suggestions = [{'value': 'song1','data': '123'}, {'value': 'song2','data': '234'}]
    return jsonify({"suggestions":suggestions})

if __name__ == "__main__":
    app.run(debug=True)

**/templates/index.html**

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.26/jquery.autocomplete.min.js"></script>
</head>

<body>
  Names:
  <input type="text" name="names" id="autocomplete1"/>

  Songs:
  <input type="text" name="songs" id="autocomplete2"/>


  <script>
  $('#autocomplete1').autocomplete({
      serviceUrl: '/search/names',
      dataType: 'json',
      onSearchComplete: function (query, suggestions) {
        console.log(query);
      }
  });

  $('#autocomplete2').autocomplete({
      serviceUrl: '/search/songs',
      dataType: 'json',
      onSearchComplete: function (query, suggestions) {
        console.log(query);
      }
  });
  </script>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 2021-07-20
    • 2014-12-07
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多