使用JQuery在Flask app中渲染结果

时间:2016-05-06 22:28:30

标签: jquery flask

到目前为止,我设法创建了一个包含文本字段和按钮的页面。用户输入文本并单击按钮后,将在控制台和命令提示符中显示搜索结果(数据库)。我需要在空<div id='empty'>

中显示结果的代码
@app.route('/search', methods=['POST'])
def search():
name =  request.form['name'];
j=CARDS_COLLECTION.find({'name':"whatever"})
for k in j:
    print k
print name
return json.dumps({'status':'OK','name':name});


@app.route('/page')
def page():
return render_template('page.html')

这是page.html上的脚本

<script type="text/javascript">$(function() {
$('button').click(function() {
    var name = $('#txtname').val();
    $.ajax({
        url: '/search',
        data: $('form').serialize(),
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });
});
});</script>

1 个答案:

答案 0 :(得分:1)

要在“div”中显示结果,您应该在成功函数内部的ajax函数内执行javascript。查看您必须执行的操作的示例。

#app.py     来自flask导入Flask,request,render_template,jsonify

app = Flask(__name__)


@app.route('/search', methods=['POST'])
def search():
    # this works and I don't know  why because we should use
    # request.get_json() to parse json data...
    name = request.form['name']
    # using the jsonify function to turn dict into json and send
    # the correct HTTP header
    return jsonify({"status": "OK", "name": name}), 200


@app.route('/')
def hello_world():
    return render_template("search.html")


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

和html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input id="search_field" type="text">
<button>Search!!</button>

<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function() {
$('button').click(function() {
    // we dont use form because we wanna send data with javascript
    // so we get the value of input into a variable
    var name_field = $("#search_field").val();
    // I wanna send the data as json documento, so we create one to put our    values
    var my_data = {
        name: name_field
    };
    $.ajax({
        url: "/search",
        data: my_data,  // here come the json data
        type: 'POST',
        success: function(response) {
            // I said that you must use parseJSON but I was wrong
            // because the data is already a JSON document and try to
            // parse it again leads to an error... so, don't use it for now
            // more details http://api.jquery.com/jquery.parsejson/
            // var data = $.parseJSON(response);

            // just to see what is comming from server
            console.log(response);

            // now we will create a div above every element on body
            // notice that I'm escaping the " for id... there are many ways and methods
            // to insert html or text, aways depends on your needs.
            $('body').prepend("<div id=\"empty\">"+response.name+"</div>");
        },
        error: function(error) {
            console.log(error);
        }
    });
});
});
</script>

</body>
</html>