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

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

问题描述

使用Flask框架无法使jQuery自动完成小部件工作。 ( http://jqueryui.com/autocomplete/#remote 这里是一个例子)


manage.py 中,我得到了以下内容:

  @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 [b]
return jsonify(json_list = results)

我的索引。 html 文件:

 < head> 
...
< link href =http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css =Stylesheet> < /链路>
< 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>
$($ b $ .ajax({
url:'{{url_for(autocomplete)}}'
})。done(function(data)自动完成({
source:data.json_list,
minLength:2
});
}); $ b $('#autocomplete' b});
< / script>
...
< / head>
< body>
...
< div>
< input name =autocompletetype =textid =autocompleteclass =form-control input-lg/>
< / div>
...
< / body>

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


GET / autocomplete HTTP / 1.1200 -
GET / HTTP / 1.1200 -
GET
/static/css/bootstrap.css HTTP / 1.1304 -
GET /static/js/jquery.js
HTTP / 1.1304 -

小工具不起作用。由于我不太了解jQuery,所以无法弄清楚导致问题的原因。有人能帮我吗?

解决方案

下面是工作的JS / jQuery和Flask代码:

  @ 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 =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,//在flask中,q将是使用request.args
},function(data){
response(data.matching_results); //来自jsonify的匹配结果
});
},
minLength:2,
select:function(event,ui){
console.log(ui.item.value); //不在你的问题中,但可能在以后帮助
}
});
})

< / script>
< / head>
< body>
< div>
< input name =autocompletetype =textid =autocompleteclass =form-control input-lg/>
< / div>
< / body>

有点解释是为了:'q'是您在jQuery中定义的搜索字词参数名称$ .getJSON ajax调用。这是传递给烧瓶,并采用 request.args.get 。数据库查询是从那里构建的,列表理解用来构造结果。请注意,列表解析不会初始化列表,也不会使用for + append组合;接下来,jsonify返回列表 results 作为一个字典包装成<$ code> matching_results 保存结果列表。不要试图使用 json.dumps 将列表返回给您的ajax调用。请参阅这里为什么(TL / DR:安全问题)。

还要注意的是,我故意改变了一些变量名,所以你可以告诉脚本/烧瓶函数看到哪个变量。例如,ajax调用没有看到列表 results ,它看到 matching_results 。这里面(现在的JavaScript的)数据对象。

获取列表 matching_results 是使用附加脚本中的模式的关键。它比简单发送列表更混乱,但更安全,并最终将允许您在客户端使用JS / jQuery进行更复杂的事情。



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



<对于更完整的jquery-autocomplete示例,请参阅使用AJAX加载数据一节 here


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.

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

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