[英]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.