码迷,mamicode.com
首页 > Web开发 > 详细

Flask Ajax Demo

时间:2015-06-01 00:50:21      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:


Python Code:

from flask import Flask, jsonify, request, render_template

app = Flask( __name__ )


@app.route( "/", methods = [ "POST", "GET" ] )
def index():
    if request.method == "POST":
        first_name = request.form.get( "first_name", "null" )
        last_name = request.form.get( "last_name", "null" )
        return jsonify( name = first_name + " " + last_name )
    else:
        return render_template( "index.html" )


if __name__ == "__main__":
    app.run(
        port = 7777,
        debug = True
    )


html code:

<html>
    <head>
        <script type=text/javascript src="{{
  url_for('static', filename='jquery.min.js') }}"></script>
        <script type="text/javascript">
            var $SCRIPT_ROOT = {{request.script_root|tojson|safe}};
            function ajaxForm() {
                $.ajax( {
                    type : "POST",
                    url : $SCRIPT_ROOT,
                    dataType : "json",
                    data : {
                        "first_name" : $( "input[name=first_name]" ).val(),
                        "last_name" : $( "input[name=last_name]" ).val(), 
                    },
                    error: function( XMLResponse ) {
                        alert( XMLResponse.responseText )
                    },
                    success : function ( data, textStatus ) {
                        $( "#name" ).text( data.name );              
                    }
                } );
                return false;            
            }
        </script>
    </head>
    <body>
        <form action="" method="post" onSubmit="return ajaxForm()">
            <input name="first_name" type="text" />
            <input name="last_name" type="text" />
            <input type="submit" />            
        </form>
        <p>Hello: <span id="name"></span></p>
    </body>
</html>


result:

技术分享




Flask Ajax Demo

标签:

原文地址:http://blog.csdn.net/pandora_madara/article/details/46293903

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!