我让计数器正常工作我很确定我的帖子开始工作了。有人可以看看我的代码并告诉我哪里出错了。代码保留了Sessions的数量。我希望忍者按钮为+2,黑客重置为1.得到所有这些,但最后两部分。任何帮助,将不胜感激。
from flask import Flask, session, render_template, url_for, request, redirect
app = Flask(__name__)
app.secret_key = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT'
def sumSessionCounter():
try:
session['counter'] += 1
except KeyError:
session['counter'] = 1
@app.route('/')
def index():
sumSessionCounter()
return render_template('index.html')
def contact():
if request.method == 'POST':
if request.form['ninja'] == session['counter'] + 2:
pass # do something
elif request.form['hacker'] == session['counter'] - session['counter'] + 1 :
pass # do something else
pass # unknown
elif request.method == 'GET':
return render_template('contact.html', form=form)
app.run(debug=True)
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="stylenew.css"></style>
<script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
</script>
</head>
<body>
<h1>{{session['counter']}}</h1>
<p><input type="submit" name="submit" value="ninja"></p>
<p><input type="submit" name="submit" value="hacker"></p>
</body>
</html>
答案 0 :(得分:0)
我认为在这里添加一些Ajax调用会更好。在app.py
中,添加路线:
@app.route('/sessionCounter')
def sessionCounter():
message = request.args.get('message', 'reset')
if message == 'add':
try:
session['counter'] += 2
except KeyError:
session['counter'] = 1
elif message == 'reset':
session['counter'] = 1
return jsonify(result=session['counter']) # need to import jsonify from flask
我还假设您使用contact.html
作为此特定HTML视图的模板。因此,您的app.py
需要一个呈现模板的路线:
@app.route('/contact')
def contact():
return render_template('contact.html', session=session)
现在在您的联系人HTML中,您需要添加JS代码来处理按钮点击并自行修改按钮:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="stylenew.css"></style>
<script type="text/javascript" src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$('button#add').bind('click', function() {
$.getJSON('/sessionCounter', {
message: 'add'
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
$(function() {
$('button#reset').bind('click', function() {
$.getJSON('/sessionCounter', {
message: 'reset'
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
</head>
<body>
<h1 id='result'>{{session['counter']}}</h1>
<p><button id="add">Ninja</button></p>
<p><button id="reset">Hacker</button></p>
</body>
</html>
现在启动您的应用,转到http://localhost:5000/contact
,然后点击:)