Flask + jquery自动完成

时间:2014-03-17 08:44:09

标签: jquery autocomplete flask

关于flask和jquery自动完成的另一个问题。我一直在阅读并尝试以下已回答的问题而没有取得任何成功:

Flask AJAX Autocomplete

Using jQuery autocomplete with Flask

特别是第二个答案完全符合我的情况。

然而由于某些原因(可能是我不理解应该做什么),回调autocomplete(..)仅在我加载页面时执行一次(并正确地自动完成NAMES中的值)但是永远不要在文本框中输入。

search.html

<head>
    <meta charset="utf-8">
    <link   rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
</head>

{{ form.autocomp.label }}: {{ form.autocomp }}

<script>
    $(function() {
        $.ajax({
            url: '{{ url_for("autocomplete") }}'
            }).done(function (data) {
                $('#autocomplete').autocomplete({
                    source: data,
                    minLength: 2
                });
            });
        });
</script>

application.py

from flask import Flask, Response, render_template, request
import json

app = Flask(__name__)

import wtforms as wt
from wtforms import TextField, Form

NAMES=["abc","abcd","abcde","abcdef"]

class SearchForm(Form):
    autocomp= TextField('autocomp',id='autocomplete')

@app.route('/autocomplete',methods=['GET'])
def autocomplete():
    search = request.args.get('term')

    app.logger.debug(search)
    return Response(json.dumps(NAMES), mimetype='application/json')

@app.route('/',methods=['GET','POST'])
def index():
    form = SearchForm(request.form)
    return render_template("search.html",form=form)

if __name__ == '__main__':
    app.run(debug=True)

2 个答案:

答案 0 :(得分:8)

试试这个

from flask import jsonify

NAMES=["abc","abcd","abcde","abcdef"]

@app.route('/autocomplete',methods=['GET'])
def autocomplete():
    search = request.args.get('term')

    app.logger.debug(search)
    return jsonify(json_list=NAMES) 

在Jquery中:

<script>
$(function() {
    $.ajax({
        url: '{{ url_for("autocomplete") }}'
        }).done(function (data) {
            $('#autocomplete').autocomplete({
                source: data.json_list,
                minLength: 2
            });
        });
    });
</script>

答案 1 :(得分:3)

它不起作用,因为建议的代码段中有一个错误打印:

from flask import jsonify
NAMES=["abc","abcd","abcde","abcdef"]
@app.route('/autocomplete',methods=['GET'])
def autocomplete():
    search = request.args.get('term')

search = request.args.get('term')'term'更改为'autocomplete'。所以正确的代码应该如下:

from flask import jsonify
NAMES=["abc","abcd","abcde","abcdef"]
@app.route('/autocomplete',methods=['GET'])
def autocomplete():
    search = request.args.get('autocomplete')