Passing data from javascript to Flask

I know how to pass data with jinja template from python to javascript, but I want to pass a javascript variable in python. I would like to do this without reloading the page. Is it possible?

+9
javascript python flask jinja2
source share
3 answers

Yes, as monkut said - I believe you want to use JSON and Javascript / jQuery.

This will allow communication with the client on the server and vice versa.

The most suitable example I found was in flash fragments / templates: http://flask.pocoo.org/docs/patterns/jquery/

+4
source share

I did a similar job in my project and would like to share my code here. I need to find out which publication is selected, and I selected the selected record as a global variable on the server side so that I can use it for later comparison. This is how I pass my selected post to Javascript.

<a class="label label-primary" onclick="myFunction({{very.id}})" > Compare</a> 

Now from Javascript to Flask.

 function myFunction(x) { $.getJSON($SCRIPT_ROOT + '/check_selected', { post: x }, function(data) { var response = data.result; console.log(response); } }); } 

This is how I return the result from the bulb using JSON.

 import json @main.route('/check_selected', methods=['GET','POST']) def check_selected(): global selected post = request.args.get('post', 0, type=int) return json.dumps({'selected post': str(post)}); 

As mentioned here , we need to enable the Google AJAX API to load jquery:

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="{{ url_for('static', filename='jquery.js') }}">\x3C/script>')</script> 
+4
source share

Create a JSON string from your view code, say jsonData and in your Jinja template write something like

 <script type="text/javascript"> var data = {{ jsonData }}; </script> 
0
source share

All Articles