问题描述
我有一个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)
Home.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}}
解决方法
fetch
是一个异步调用,您实际上没有在重定向。您正在发回html响应。您的方法存在几个问题,但让我们从这里开始:
fetch('/getjson',{
method: 'POST',credentials:"include",cache:"no-cache",headers: {
'Content-Type': 'application/json',},body: JSON.stringify(t),})
.then(response => response.json())
.then(data => {
console.log('Success:',data);
window.location.replace(window.location.href + "comp");
})
.catch((error) => {
console.error('Error:',error);
});
然后:
from flask import Flask,request,flash,url_for,redirect,render_template,session,jsonify
# receive json object,set to session,then send back
@app.route('/getjson',methods=['POST'])
def getjson():
req=request.get_json()
session['my_var']=req # create session variable
return jsonify({"sent_to_session":req})