【发布时间】:2018-08-28 21:31:15
【问题描述】:
我可以在这里实现本教程:https://pythonprogramming.net/jquery-flask-tutorial/
但是,我想扩展它并使用来自 html 的输入作为变量来执行其他代码。我无法像过去那样获取变量:
lang =request.form['proglang']
并像这样引用它以显示在 html 模板上:
<h3>You responded with: {{ lang }} </h3>
请告诉我如何从我的 html 输入中获取变量
@app.route('/interactive', methods=['GET', 'POST'])
完整代码html模板:
{% block body %}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#process_input').bind('click', function() {
$.getJSON('/background_process', {
proglang: $('input[name="proglang"]').val(),
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
</head>
<body>
<div class='container'>
<h3>Welcome! Which is the best programming language of them all?</h3>
<form>
<input type=text size=5 name=proglang>
<a href=# id=process_input><button class='btn btn-default'>Submit</button></a>
</form>
<p id=result></p>
</div>
</body>
<body>
<div class='container'>
<h3>You responded with: {{ lang }} </h3>
</div>
</body>
{% endblock %}
完整的代码烧瓶:
from flask import Flask
from flask import render_template, url_for, request, redirect
from flask import jsonify
app = Flask(__name__)
@app.route('/interactive', methods=['GET', 'POST'])
def interactive():
try:
lang =request.form['proglang']
except:
lang = '1234'
return render_template('interactive_v2.html', lang=lang)
@app.route('/background_process')
def background_process():
try:
lang = request.args.get('proglang', 0, type=str)
if lang.lower() == 'python':
return jsonify(result=lang)
else:
return jsonify(result='Try again.')
except Exception as e:
return str(e)
if __name__ == '__main__':
app.run(debug=True)
【问题讨论】: