Отправить переменные от Python Flask до HTML - PullRequest
0 голосов
/ 26 апреля 2020

У меня следующая проблема: я хочу отправить некоторые данные на Html с 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.

1 Ответ

0 голосов
/ 26 апреля 2020

Хорошо, поэтому передавать переменные от python flask до html просто. Импортируйте json

. Создайте объект словаря с ключом, какой хотите, и присвойте этому ключу свою переменную. Jobj = {'name': name}. Теперь выведите этот объект как json и передайте в качестве аргумента return render_template ( 'htmlfile. html', res = json .dumps (jobj))

Теперь вы сможете получить доступ к res json в JavaScript в htmlfile. html

Var res = JSON .parse ('{{res | safe}}'); console.log (res.name);

...