【发布时间】:2020-08-18 15:56:21
【问题描述】:
我有一个 Javascript 代码将变量从 Home.html 发送到 Flask,Flask 将它发送到 Comp.html。但似乎 Comp.html 一直显示先前或错误的变量。有人可以帮助解决问题吗?单击“ABC”时,Comp.html 应显示 ABC。
Flask 应用代码:
from flask import Flask, request, flash, url_for, redirect, render_template, session
import random
import json
app = Flask(__name__)
@app.route('/')
def show_all():
return render_template('home.html')
# receive json object and pass it to homepage
@app.route('/getjson', methods=['POST'])
def getjson():
req=request.get_json()
session['my_var']=req # create session variable
return redirect(url_for('comp')) # send session variable to another route
@app.route('/comp')
def comp():
my_var2 = session.get('my_var', None) # receive session variable
return render_template('comp.html', my_var2=my_var2)
if __name__ == '__main__':
app.secret_key = 'mysecretkey' # needed for session to work
app.run(debug=True)
主页.html:
<!DOCTYPE html>
<html lang = "en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<a href="/comp" onclick='clickfunc(this)'>DBS</a><br>
<a href="/comp" onclick='clickfunc(this)'>SCI</a><br>
<a href="/comp" onclick='clickfunc(this)'>ABC</a><br>
<a href="/comp" onclick='clickfunc(this)'>DDD</a><br>
</body>
<script>
function clickfunc(obj) {
var t = $(obj).text();
alert(t);
fetch(window.location.href+'getjson',{
method:"POST",
credentials:"include",
body:JSON.stringify(t),
cache:"no-cache",
headers: new Headers({
"content-type":"application/json"
})
})
}
</script>
</html>
comp.html:
This is the redirected page
<br>
{{my_var2}}
【问题讨论】:
标签: javascript python session flask jinja2