使用jQuery自动完成与瓶 [英] Using jQuery autocomplete with Flask

查看:141
本文介绍了使用jQuery自动完成与瓶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经被问过了,我认为我做了什么我见过,但我真的不知道我在做什么错。我不知道了很多关于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>

由该瓶窗体类生成的表单:

The form is generated by this Flask form class:

class SearchForm(Form):
    function_name = TextField('function_name', validators = [Required()])

和这里的自动完成功能:

And here is the autocomplete function:

@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?

推荐答案

更新:

自动完成不自动处理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]))

但你很可能提高查询直接返回一个字符串列表。你需要,如果你想与帮助后整个code。

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.

这篇关于使用jQuery自动完成与瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆