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

How can I get the template and Python to communicate in Flask?

例如,如果我在index.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)

因此,在三个 div 块中。当我点击其中任何一个时。我想让程序知道我点的是哪一个,把id(1,2,3)的值传到python里的data变量里,这样我就可以在"expert.html".[=上使用了13=]

有什么好的方法可以实现它?先谢谢你了!

您可以使用按钮代替 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"对象传回给ajaxindex.html 模板中。从模板中的 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'])