[英]Read a variable name in Javascript from Flask
我使用 render_template 方法將變量從 Flask 傳遞到 JavaScript。
我關注了這篇文章:將變量從燒瓶傳遞到 javascript ,但它對我不起作用
這是我的代碼:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/debug')
def index_debug():
return render_template('index.html', debug=True)
我想從 JavaScript 文件中讀取它。 我嘗試使用這種方法:
這是我的 html 文件:
<head>
<script type="text/javascript">
var debugMode = {{ debug }};
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js" crossorigin="anonymous"></script>
<script src="/static/index.js"></script>
</head>
但是當我嘗試在我的 index.js 中訪問這個變量時。 變量 debugMode 未定義。
嘗試這個
<head>
<script type="text/javascript">
window.debugMode = {{ debug }};
</script>
<script src="/static/index.js"></script>
</head>
如果你想從 JS 中的 HTML 讀取一個變量,你應該在窗口范圍內聲明這個變量並像這樣讀取 JS 文件。
const myNewVar = window.debugMode
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.