admin管理员组文章数量:1323035
I know that you can simply call a variable from Flask by including return render_template('index.html', variable=newvariable)
in the Python file and
<script>
var JSVAR = '{{ newvariable }}';
</script>
in the index.html file. But what if I want to pass that variable onto a purely Javascript file that's included within the index.html file? I'm thinking I need to create an HTML 'variable' of sorts using the id parameter then use jQuery to call it, but I can't figure out the syntax.
Any ideas?
I know that you can simply call a variable from Flask by including return render_template('index.html', variable=newvariable)
in the Python file and
<script>
var JSVAR = '{{ newvariable }}';
</script>
in the index.html file. But what if I want to pass that variable onto a purely Javascript file that's included within the index.html file? I'm thinking I need to create an HTML 'variable' of sorts using the id parameter then use jQuery to call it, but I can't figure out the syntax.
Any ideas?
Share Improve this question asked Nov 27, 2013 at 6:33 quantumtremorquantumtremor 3,9372 gold badges19 silver badges20 bronze badges3 Answers
Reset to default 3Exposing a function and making an ajax call to it isn't a bad way to go. That approach es with the benefit of leaving a clear trail of function calls for maintainers.
http://api.jquery./jQuery.ajax/
http://flask.pocoo/docs/patterns/jquery/
The second link has a more detailed description, but the general idea is you have a Flask app set up to handle requests from the browser, and in that application you set up a method that can have requests sent to it that will take care of passing your variable back out to the js client.
In the js script you then make an ajax call to that method's url, and have a callback function that processes the response. This approach can do some really, really cool things.
If you're not familiar with ajax, it might be useful to Google some tutorials. This one is half way decent as an overview: http://www.tutorialspoint./ajax/ajax_in_action.htm
Just came across this same issue, here is what I did
from jinja2.environment import Template
def render_js():
file_content = open(path_to_jsfile, 'r').read()
template = Template(file_content)
return template.render(arg1='value1', arg2='value2')
You can access the variable using a data attribute on an html element. You can then use a querySelector to access the value in that data attribute.The data-chart attribute holds the variable from the flask app
const chart-data = document.querySelector("#chart-div").getAttribute("data-chart")
That should get hold of the variable from the flask app.
本文标签:
版权声明:本文标题:jquery - Passing variables from Flask (python) into a Javascript file separate from the HTML file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742108234a2421123.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论