【发布时间】:2022-09-23 15:42:29
【问题描述】:
我想在我的表单上自动完成,我正在使用 ajax。
使用下面的代码,获取请求正在通过,但它总是给出\'没有搜索结果
ajax代码
<script type=\"text/javascript\">
$(function() {
$(\'#{{item.name}}\').autocomplete({
source:function(request, response) {
$.getJSON(\"{{\'/autocomplete/\' + keypair.table + \'/\' + item.name}}\",{
q: request.term, // in flask, \"q\" will be the argument to look for using request.args
}, function(data) {
response(data.keyitem); // matching_results from jsonify
});
},
minLength: 2,
datatype: \"json\",
select: function(event, ui) {
console.log(ui.item.value); // not in your question, but might help later
}
});
})
</script>
我的烧瓶 python 代码:
from cs50 import SQL
from flask import jsonify
# inspiration from https://stackoverflow.com/questions/34704997/jquery-autocomplete-in-flask
# Pro Grammer S: https://stackoverflow.com/users/19920475/pro-grammer-s
@app.route(\"/autocomplete/<tablename>/<columnname>\", methods=[\'GET\'])
def autocomplete_function(tablename, columnname):
# Check whether the table is in the available tables first
if tablename in formsdict:
# If the tablename exists, get its column names
columnames = ophalenkolomnamen(db, tablename)
# Check whether the columnname requested is in the column names
if columnname in columnames:
# Get additional search arguments (to insert in the like format)
q = str(\"%\" + request.args.get(\'q\') + \"%\")
print(q)
# get the requested autocomplete list
# using CS50 to prevent SQL injection attacks
string = f\"SELECT * FROM `{tablename}` WHERE `{columnname}` LIKE ?;\"
autocompletelist = db.execute(string, q)
return jsonify(autocompletelist)
else:
return []
路由的响应是具有正确值对的字典列表:
[{ item.name : value1 },{ item.name : value2 },...]
我还收到了来自 Ajax 函数的请求(我可以在终端中打印出来)
我究竟做错了什么?我已经找了几个小时,但找不到原因:(
标签: jquery ajax api flask request