我正在准备一个演示,这是我第一次做#34; 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)
我需要一个非常简单的例子(没有什么花哨的)才能做到这一点..
由于
答案 0 :(得分:4)
如何使用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>