【问题标题】:Why Jinja keeps displaying previous value为什么 Jinja 一直显示以前的值
【发布时间】: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


    【解决方案1】:

    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})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2016-03-16
      • 1970-01-01
      • 2020-08-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多