<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Flask JQuery</title> <!-- 插入jquery --> <script src="{{url_for('static', filename='jquery.js')}}"></script> <script type=text/javascript> var $SCRIPT_ROOT = {{request.script_root|tojson|safe}}; </script> <script type=text/javascript> $(function() { function submit_form(e) { $.getJSON($SCRIPT_ROOT + '/add', { a: $('input[name="a"]').val(), b: $('input[name="b"]').val(), now: new Date().getTime() }, function(data) { $('#result').text(data.result); }); }; // 绑定click事件 $('#calculate').bind('click', submit_form); }); </script> </head> <body> <p> <input type=text size=5 name=a> + <input type=text size=5 name=b> = <span id=result>?</span> </p> <p><input type="button" id="calculate" value="计算"></p> </body> </html>
# -*- coding: utf-8 -*- from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route("/") def index(): # 主页面 return render_template("main.html") @app.route('/add') def add_numbers(): a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result = a + b) if __name__=="__main__": app.run(host = "0.0.0.0",port = 8080, debug = True)
原文地址:http://blog.csdn.net/xukai871105/article/details/38148757