我正在使用 Python 和 Flask 开发一个 Web 项目。我只是想知道我是否可以在我的外部 javascript 文件中访问 python 发送的参数?它适用于 html 文件或嵌入在 html 文件中的 js,但当 javascript 为外部时则不行。
见下文。
python 代码
@app.route('/index')
def index():
return render_template('index.html', firstArg = 2, secondArg = 3)
index.html 代码
...
<body>
<p>The first arg is {{firstArg}}.</p>
<script src="index.js"></script>
</body>
...
还有 index.js 文件
window.onload=function(){
console.log('{{secondArg}}');
};
所以第一个参数在 html 文件中是正确的,但第二个在 js 文件中不起作用。浏览器显示 Unexpected token {
.
可能在外部js中无法使用?
否则我需要在 html 中插入 secondArg 作为输入数据并在 js 文件中获取它,但它不是很干净。
如果有人可以帮忙,谢谢。
最佳答案
您的 flask 实例可能不提供 index.js,但它肯定不会由您的模板引擎处理,即使它不会与请求的 html 具有相同的上下文。
我认为最干净的解决方案是在您的 index.js
中有一个启动函数并从 html 文件中调用它:
<body>
<p>The first arg is {{firstArg}}.</p>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
yourInitFunction({{secondArg}});
</script>
</body>
你也可以告诉 flask 路由 index.js:@yourapp.route('index.js')
就像你使用 route('/index' )
但是这可能不是一个好主意。
关于javascript - 在外部 javascript 文件中使用 Jinja2 模板引擎,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21956500/