问题描述
这个问题以前有人问过,我想我已经做了我在那里看到的,但我真的不知道我做错了什么.我对 jQuery 了解不多,但我会尽力解释我正在尝试做什么.
This question has been asked before, and I think I've done what I've seen there, but I don't really know what I'm doing wrong. I don't know a lot about jQuery, but I'll do my best to explain what I'm trying to do.
我想根据来自数据库的查询自动完成,所以我的模板中有这个:
I want to autocomplete based on a query from a database, so I have this in my template:
<script type="text/javascript">
$(function() {
$( "#function_name" ).autocomplete({
source: '{{url_for("autocomplete")}}',
minLength: 2,
});
});
</script>
<form id="function_search_form" method="post" action="">
{{form.function_name}}
</form>
表单是由这个 Flask 表单类生成的:
The form is generated by this Flask form class:
class SearchForm(Form):
function_name = TextField('function_name', validators = [Required()])
这里是自动完成功能:
@app.route('/autocomplete')
def autocomplete():
results = []
search = request.args.get('term')
results.append(db.session.query(Table.Name).filter(Table.Name.like('%' + search + '%')).all())
return dumps(results)
因此 jQuery 应该转到自动完成功能并获取一些 JSON 以进行自动完成.至少我认为这就是正在发生的事情.我在这里做错了什么?
So the jQuery should go to the autocomplete function and get some JSON back to autocomplete with. At least I think that's what's going on. What am I doing wrong here?
推荐答案
更新:
autocomplete
如果你给它一个 URL,它不会自动处理 Ajax 请求,你必须手动完成:
autocomplete
doesn't handle the Ajax request automatically if you give it a URL, you must do it manually:
$(document).ready(function() {
$.ajax({
url: '{{ url_for("autocomplete") }}'
}).done(function (data) {
$('#function_name').autocomplete({
source: data,
minLength: 2
});
});
}
您可能需要修改处理返回数据的方式,具体取决于 API 返回的内容.
You might have to modify the way you handle the returned data, depending on what your API returns.
更新 2:
您在服务器端的查询结果如下所示:
The result of your query on the server side looks like this:
[[["string1"], ["string2"], ... ["stringn"]]]
您可以在发送之前将其展平:
You can flatten it before sending it:
import itertools
flattened = list(itertools.chain.from_iterable(result[0]))
但是您可能可以改进您的查询以直接返回字符串列表.如果您需要这方面的帮助,则需要发布整个代码.
But you could probably improve your query to return a list of strings directly. You will need to post the whole code if you want help with that.
这篇关于在 Flask 中使用 jQuery 自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!