[英]Autocomplete search box and pass value to flask
我正在准备演示,这是我第一次做“web dev”。 所以,可能完全是一个noob问题,但这是我想要做的。
我想有两个自动填充的搜索框作为打字。
First search box: name
Second search box: song
我有两个文件names.txt和songs.txt
因此,我们的想法是,当用户输入名称时,它会从names.txt中读取以生成自动完成,当用户输入歌曲时,搜索框会根据songs.txt进行自动填充。
然后将这些值传递给后端的烧瓶app。
@app.route('/search', method=['post'])
def process():
return name, song, and list of other songs with score (list a table)
我需要一个非常简单的例子(没什么特别的),只是这样做..
谢谢
如何使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.