Skip to content
Advertisement

List of list from flask to JS

My Python code calculate coordonates of devices and put it in a list. So i get a list of list in a python var my_devices_list = [ ["name1", 11.1, 22.2] , ["name2", 33.3, 44.4] ]

i’m trying to pass this list to my JS code

my python code :

@app.route('/map')
def map():
    my_devices_list = [ ["name1", 11.1, 22.2] , ["name2", 33.3, 44.4] ]
    return render_template('map.html', data=my_devices_list)

my JS code :

someJavaScriptVarTabAll = '{{ data }}';
alert(someJavaScriptVarTabAll)

the alert I get from the JS alert :

[['name1', 11.1,22.2], [['name2', 33.3, 44.4]]

What i would like to do: a for loop to place waypoints on my map like:

{% for device in data %}
   wayPointOnMap = (name = device[0], coord_x = device[1], corrd_y = device[2])
{% endfor%}

I know that the following code works, but i can’t get a loop that way

    someJavaScriptVar0 = '{{ data[0] }} ';
    someJavaScriptVar1 = '{{ data[1] }} ';
    someJavaScriptVar2 = '{{ data[2] }} ';
    alert(someJavaScriptVar0 )
    alert(someJavaScriptVar1 )
    alert(someJavaScriptVar2 )

I try to pass the list from the python code using json.dumps(), but i can’t loop on it in my JS code

@app.route('/map')
def map():
    my_devices_list = [ ["name1", 11.1, 22.2] , ["name2", 33.3, 44.4] ]
    return render_template('map.html', data=json.dumps(my_devices_list))

Thanks for your help!!

Advertisement

Answer

Instead of attempting to format the list as an array in the JS file, you can send a request to the web app via AJAX to get the proper jsonified response. First, update your routes to include another route that receives the AJAX request and returns the result:

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

@app.route('/get-map', methods=['POST']):
def get_map():
   return flask.jsonify({'map':[ ["name1", 11.1, 22.2] , ["name2", 33.3, 44.4] ]})

Then, in your JS file (after adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>) to your HTML header):

$.ajax({
    url: "/get-map",
    type: "POST",
    data: {},
    success: function(response) {
       //response.map stores the map array
       for (var [v1, v2, v3] of response.map){
          console.log(v1)
          console.log(v2)
          console.log(v3)
       }
    }
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement