如何让模板和Python在Flask中进行通信?

2024-05-19 12:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我在索引.html地址:

<div id='1'></div>
<div id='2'></div>
<div id='3'></div>

我用Python编写了以下代码:

 from flask import *
 @app.route("/")
 def index():
     return render_template("index.html")

 @app.route('/experts')
 def route1():
     return render_template("experts.html", data=data)

所以,在三个分区中。当我点击其中任何一个的时候。我想让程序知道我点击的是哪一个,并将id(1,2,3)的值传递到python中的数据变量中,这样我就可以在专家.html". 你知道吗

我有什么好办法可以做到这一点?提前谢谢!你知道吗


Tags: 代码fromdividappdataindexreturn
1条回答
网友
1楼 · 发布于 2024-05-19 12:35:29

您可以使用按钮来代替divs。这样,可以在前端使用ajax检索所单击按钮的id并将其传递给后端:

"index.html"

<html>
 <body>
  <button id='1'>Button1</button>
  <button id='2'>Button2</button>
  <button id='3'>Button3</button>
</body>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script>
   $(document).ready(function() {
     $('button').click(function(event) {
       var the_id = event.target.id;
        $.ajax({
         url: "/get_id",
         type: "get",
         data: {the_id: the_id},
         success: function(response) {
           window.location.replace('/experts');
        },
        error: function(xhr) {
         //Do Something to handle error
        }
       });           
   });
 </script>
</html>

然后,可以创建接收id的路由,来自ajax的结果可以存储在flask.session,并且可以将“success”对象传递回index.html模板中的ajax。从模板中的jquery,应用程序可以重定向到/expert

import flask
app = flask.Flask(__name__)
app.secret_key = 'SOME_SECRET_KEY'
@app.route('/get_id')
def expert():
  button_id = flask.request.args.get('the_id')
  flask.session['button_id'] = button_id
  return flask.jsonify({'success':True})

@app.route('/experts', methods=['GET'])
def experts():
  return render_template("experts.html", data=flask.session['button_id'])

相关问题 更多 >