简体   繁体   English

从 Flask 读取 Javascript 中的变量名称

[英]Read a variable name in Javascript from Flask

I am passing variable from Flask to JavaScript using the method render_template.我使用 render_template 方法将变量从 Flask 传递到 JavaScript。

I followed this post: Passing variables from flask to javascript , but it is not working for me我关注了这篇文章:将变量从烧瓶传递到 javascript ,但它对我不起作用

Here is my code:这是我的代码:

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

@app.route('/debug')
def index_debug():
    return render_template('index.html', debug=True)

I would like to read it from a JavaScript file.我想从 JavaScript 文件中读取它。 I tried using this method:我尝试使用这种方法:

this is my html file:这是我的 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>

But when i try accessing this variable in my index.js.但是当我尝试在我的 index.js 中访问这个变量时。 the variable debugMode is undefined.变量 debugMode 未定义。

Try this尝试这个

<head> 
 <script type="text/javascript">
    window.debugMode = {{ debug }};
 </script>
 <script src="/static/index.js"></script>
</head>

If you want to read a variable from HTML in JS you ought to declare this var in window scope and read in JS file like this.如果你想从 JS 中的 HTML 读取一个变量,你应该在窗口范围内声明这个变量并像这样读取 JS 文件。

const myNewVar = window.debugMode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM