Flask 中的 jQuery 自动完成 [英] jQuery autocomplete in Flask

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

问题描述

无法使 jQuery 自动完成小部件与 Flask 框架一起使用.(http://jqueryui.com/autocomplete/#remote 这里是一个例子)
ma​​nage.py 中,我得到了以下内容:

@app.route('/autocomplete', methods=['GET'])定义自动完成():结果 = []search = request.args.get('自动完成')对于 db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%')).all() 中的 mv:结果.附加(mv [0])返回 jsonify(json_list=results)

我的index.html文件:

 ...<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="样式表"></link><script src="../static/js/jquery.js"></script><script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script><script type="text/javascript">$(函数(){$.ajax({网址:'{{ url_for(自动完成")}}'}).完成(功能(数据){$('#autocomplete').自动完成({来源:data.json_list,最小长度:2});});});...<身体>...<div><input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>

...

看起来 firefox 中的开发工具不会返回任何错误.终端返回以下内容:

<块引用>

"GET/自动完成 HTTP/1.1" 200 -
"GET/HTTP/1.1" 200 -
"GET/static/css/bootstrap.css HTTP/1.1" 304 -
"GET/static/js/jquery.jsHTTP/1.1" 304 -

该小部件不起作用.因为我对 jQuery 不太了解,所以我无法弄清楚是什么导致了这个问题.有人可以帮我吗?

解决方案

以下是 JS/jQuery 和 Flask 代码:

@app.route('/autocomplete', methods=['GET'])定义自动完成():search = request.args.get('q')查询 = db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%'))结果 = [mv[0] for mv in query.all()]返回 jsonify(matching_results=results)

HTML/jQuery:

<link href="//code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="样式表"></link><script src="//code.jquery.com/jquery-2.2.0.min.js"></script><script src="//code.jquery.com/ui/1.10.2/jquery-ui.js" ></script><script type="text/javascript">$(函数(){$("#autocomplete").autocomplete({来源:功能(请求,响应){$.getJSON("{{url_for('autocomplete')}}",{q: request.term,//在flask 中,"q" 将是使用 request.args 寻找的参数},功能(数据){响应(data.matching_results);//来自 jsonify 的匹配结果});},最小长度:2,选择:功能(事件,用户界面){控制台日志(ui.item.value);//不在您的问题中,但稍后可能会有所帮助}});})<身体><div><input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>

有一点说明:'q' 是您在 jQuery 的 $.getJSON ajax 调用中定义的搜索词参数名称.它传递给flask,并使用request.args.get 获取.数据库查询由此构建,并使用列表理解来构建结果.请注意,对于列表推导式,您不会初始化列表,也不会使用 for+append 组合;一条优雅的线条无所不能.

接下来,jsonify 返回列表 results 包装成字典,键 matching_results 保存结果列表.不要试图使用 json.dumps 将列表返回给您的 ajax 调用.请参阅此处为什么(TL/DR:安全问题).

另请注意,我特意更改了一些变量名称,以便您可以判断哪个脚本/烧瓶函数看到"了哪个变量.例如,ajax 调用没有看到列表 results,它看到了 matching_results.这在(现在是 javascript 的)data 对象中.

要获取列表 matching_results 是关键,请使用附加脚本中的模式.它比简单地发送列表更麻烦,但更安全,最终将允许您使用 JS/jquery 在客户端做更复杂的事情.

最后,select 选项将用户的选择打印到开发者控制台,仅供参考,以便您可以实际响应用户的选择.

有关更完整的 jquery-autocomplete 示例,请参阅使用 AJAX 加载数据"部分 这里.

Can't make jQuery autocomplete widget work with Flask framework. (http://jqueryui.com/autocomplete/#remote here is an example)
In manage.py I got the following :

@app.route('/autocomplete', methods=['GET'])
def autocomplete():
    results = []
    search = request.args.get('autocomplete')
    for mv in db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%')).all():
        results.append(mv[0])
    return jsonify(json_list=results) 

My index.html file:

    <head>
    ...
    <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
    <script src="../static/js/jquery.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>


    <script type="text/javascript">
    $(function() {
        $.ajax({
            url: '{{ url_for("autocomplete") }}'
            }).done(function (data) {
                $('#autocomplete').autocomplete({
                    source: data.json_list,
                    minLength: 2
                });
            });
        });
    </script>
    ...
    </head>
    <body>
    ...
       <div>
          <input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>
       </div>
    ...
    </body>

Looks like dev tools in firefox don't return any errors. The terminal returns the following:

"GET /autocomplete HTTP/1.1" 200 -
"GET / HTTP/1.1" 200 -
"GET /static/css/bootstrap.css HTTP/1.1" 304 -
"GET /static/js/jquery.js HTTP/1.1" 304 -

The widget just doesn't work. Since I don't know much about jQuery I can't figure out what causes the problem. Can anybody help me please ?

解决方案

Below is working JS/jQuery and Flask code:

@app.route('/autocomplete', methods=['GET'])
def autocomplete():
    search = request.args.get('q')
    query = db_session.query(Movie.title).filter(Movie.title.like('%' + str(search) + '%'))
    results = [mv[0] for mv in query.all()]
    return jsonify(matching_results=results)

HTML/jQuery:

<head>
<link href="//code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

<script type="text/javascript">
$(function() {
    $("#autocomplete").autocomplete({
        source:function(request, response) {
            $.getJSON("{{url_for('autocomplete')}}",{
                q: request.term, // in flask, "q" will be the argument to look for using request.args
            }, function(data) {
                response(data.matching_results); // matching_results from jsonify
            });
        },
        minLength: 2,
        select: function(event, ui) {
            console.log(ui.item.value); // not in your question, but might help later
        }
    });
})

</script>
</head>
<body>
    <div>
        <input name="autocomplete" type="text" id="autocomplete" class="form-control input-lg"/>
    </div>
</body>

A bit of explanation is in order: 'q' is your search term argument name as defined in jQuery's $.getJSON ajax call. That's passed to flask, and picked up using request.args.get. The database query is constructed from that, and a list comprehension is used to construct the results. Note that with list comprehensions you don't initialize the list, nor do you use a for+append combination; one elegant line does everything.

Next, jsonify returns the list results wrapped as a dictionary with the key matching_results holding the results list. Do not be tempted to use json.dumps to return a list to your ajax call. See here why (TL/DR: security concerns).

Note also that i've deliberately changed some variable names so you could tell what script/flask function 'sees' which variable. E.g., the ajax call doesn't see the list results, it sees matching_results. And that's inside (now javascript's) data object.

To grab the list matching_results is the key for, use the pattern in the attached script. It's messier than simply sending a list, but more secure, and eventually will allow you to do more sophisticated things on the client-side using JS/jquery.

Finally, the select option prints the user's selection to the developer console, just for reference so you can actually respond to a user's selection.

For a more complete jquery-autocomplete example see the 'Load Data with AJAX' section here.

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆