Pass JavaScript variable to Flask url_for

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have an endpoint that takes a value in the url and produces some content that will be inserted into a div. I want to build the url with url_for using a JavaScript variable. However, $variable1 is passed as a string, rather than the value of variable1. How can I pass the value of a JavaScript variable to url_for?

function myFunction() {     var variable1 = "someString"     $('#demo').load(         "{{ url_for('addshare2', share = '$variable1') }}"     ); } 

回答1:

You can't evaluate JavaScript in Jinja. You're trying to generate a url on the server side while Jinja is rendering, but you're referencing a variable that is only available in the JavaScript running on the client browser.

Building the url on the client side is the most straightforward fix. (I don't know what your route looks like, so here's an example.)

$('#demo').load('/url/for/addshare2/' + variable1); 

However, this isn't very useful because you can't use url_for, so you have to hard-code the urls. This is a good sign that what you want is an AJAX endpoint that you pass parameters to, rather than an endpoint that contains values.

@app.route('/addshare2', methods=['POST']) def addshare2():     share = request.json['share']     ...     return jsonify(result=...) 

Now you can generate the url with url_for, and pass the parameters as form data.

$.post(     '{{ url_for('addshare2') }}',     {share: variable1},     function (data) {         // do something with data on successful response     } ); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!