【发布时间】:2021-12-28 21:16:55
【问题描述】:
您好,我想在 Flask 路由中使用从 ajax 调用获得的数据。请参阅下面的棕褐色示例。应用程序在 button_val() 中正确获取并打印数据,但不会在 test() 中闪烁任何值:为什么?
提前谢谢你
Flask 应用
from flask import Flask, flash, render_template, request
class dataStore():
y = None
data = dataStore()
app = Flask(__name__)
@app.route('/get_button_val')
def button_val():
resp = request.args.get('resp')
print(f'<-- {resp}')
data.y = resp
return resp
@app.route("/", methods=['GET', 'POST'])
def test():
if request.method == 'POST':
if data.y == 11:
flash('a')
if data.y == 10:
flash('b')
return render_template('test.html')
if __name__ == '__main__':
app.run(debug=True)
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="/static/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Buttons via AJAX</h2>
<button class="button1" data="11">Yes</button>
<button class="button2" data="10">No</button>
<script>
$(document).ready(function () {
$('.button1, .button2').click(function (e) {
e.preventDefault();
var val = $(this).attr('data');
$.ajax({
url: '/get_button_val',
data: { resp: val },
success: onSuccess,
error: onError,
});
});
});
</script>
{% for msg in get_flashed_messages()%}
<h3> {{msg}} </h3>
{% endfor%}
</body>
</html>
【问题讨论】: