【问题标题】:Send variables from Python Flask to HTML将变量从 Python Flask 发送到 HTML
【发布时间】:2020-08-09 11:31:43
【问题描述】:

我有以下问题: 我想通过 HTML 中的 Click 按钮从 Python 向 Html 发送一些数据,但是我点击了它根本不起作用的按钮。 这是我的代码: *

python.py:

from flask import Flask, render_template, flash, Markup, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('new.html')

@app.route('/SomeFunction', methods = ['POST', 'GET'])
def SomeFunction():
    if request.method == 'GET':
         text = 'Name'  
    print("result:")
    return render_template("new.html",text = text)

if __name__ == '__main__':
   app.run()

这是我的 Html:

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>
<div class="flashes">
  {% for message in get_flashed_messages()%}
    {{ message }}
  {% endfor %}
</div>
    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  
<script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { }, function(data) { }); return false; }); }); </script> 

</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
    <p>text: {{text}}</p>

</body>    

</html>

所以我想要的是当我按下输入按钮时,它将显示 python 中定义的名称。也许还有其他方法可以使它起作用,但我需要在 python 中。

【问题讨论】:

    标签: python html flask python-requests


    【解决方案1】:

    好的,所以将变量从 python flask 传递到 html 很容易。

    Import json
    

    用任何你想要的键创建一个字典对象并将你的变量分配给那个键

    jobj = { 'name' : name }
    

    现在将此对象转储为 json 并作为参数传递

    return render_template('htmlfile.html', res=json.dumps(jobj))
    

    现在您可以在 htmlfile.html 中的 JavaScript 中访问 res json

    <Script>
    
    var res = JSON.parse(' {{ res | safe }} ');
    console.log(res.name);
    
    </Script>
    

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多