如果我手动填充列表,则我的自动完成表单可以正常工作。但是,如果我从db填充,则不会填充下拉列表。
HTML / JS
<div style="text-align: center;">
{% from "_formhelpers.html" import render_field %}
<form method="POST" action="/">
<dl id="autocomplete" style="display:inline-block;"> .
{{render_field(form.search) }}
</dl>
<button id="searchbutton" type="submit" style="display: inline-block;" class="btn btn-outline-success my-2 my-sm-0" onclick="fetchlist(); return false;">Search</button>
</form>
</div>
<script>
$(function() {
$("#autocomplete").autocomplete({
source:function(request, response) {
$.getJSON("{{url_for('autocomplete')}}",{
q: request.term,
}, function(data) {
response(data.cities);
});
},
minLength: 2,
select: function(event, ui) {
console.log(ui.item.value);
}
});
})
function fetchlist() {
if (document.getElementById('searchbutton').onclick) {
document.getElementById('list').style.display = 'inline';
}
else document.getElementById('list').style.display = 'inline';
}
烧瓶
@app.route('/_autocomplete', methods=['GET'])
def autocomplete():
c, conn = connection()
qry = "SELECT Distinct PhoneNumber FROM webappdb.posts"
c.execute(qry)
x = c.fetchall()
cities= list(chain.from_iterable(x))
#cities = [x for x in c.fetchall()]
print(cities)
'''
cities = [
"123",
"12"]'''
return Response(json.dumps(cities), mimetype='application/json')
@app.route('/', methods=['GET', 'POST'])
def homepage():
try:
form=SearchForm(request.form)
global d1
d1 =""
if request.method == "POST":
s1 = form.search.data
c,conn = connection()
qry = "SELECT FirstName, LastName FROM posts WHERE PhoneNumber LIKE (%s)"
c.execute(qry, s1)
d1 = c.fetchall()
c.close()
conn.close()
print(d1)
else: print('error')
return render_template("index.html", data=d1, form = form)
except Exception as e:
return(str(e))
理想情况下,我希望用户输入信息,并且自动完成功能会返回并过滤数据库中的数据。用户找到所需的内容后,就会根据该人的电话号码提取信息。