[英]Send variables from Python Flask to HTML
我有以下問題:我想從 Python 向 Html 發送一些數據,點擊 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 flask 傳遞到 html 很容易。 進口json
用任何你想要的鍵創建一個字典 object 並將你的變量分配給那個鍵 jobj = { 'name': name } 現在將這個 object 轉儲為 json 並作為參數傳遞,res=jsonfiledump(htmlfile.html(htmlfile.html'工作j))
現在您將能夠訪問 htmlfile.html 中 JavaScript 中的 res json
var res = JSON.parse(' {{ res | safe }} '); console.log(res.name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.