Pradeep Kumar Anumala
Pradeep Kumar Anumala

Reputation: 73

How to pass data from python to javascript in web2py

I see some relevant posts to my query.

Tornado is used in the below link How to pass variable from python to javascript

I know that it can be done using json but I am not clear how to implement it. In the web2py default controller I am returning a dictionary which contains the latitudes and longitudes.

def index():
    lat_long_list=[]
    info1 = {'lat':'1.0032','long':'2.00003','name':'Akash'}
    info2 = {'lat':'1.2312','long':'-1.0034','name':'Kalyan'}
    lat_long_list.append(info1)
    lat_long_list.append(info2)
    return dict(lat_long_list=lat_long_list)

In java script I want to iterate through the list of dictionaries and mark the points on the google maps.

I cannot say

<script>
 {{ for lat_long_rec in lat_long_list :}}
 var name = {{=lat_long_rec['name']}}
 {{ pass }}
</script>

This fails. An alternative to handle this is to write the list into an xml and from javascript read the file but I dont want to achieve it this way as writing to file is non performant. Let me know how best this can achieved.

Upvotes: 5

Views: 2115

Answers (1)

Anthony
Anthony

Reputation: 25536

Convert the Python list to JSON and pass that to the view to insert in the Javascript code:

    from gluon.serializers import json
    return dict(lat_long_list=json(lat_long_list))

In the view:

<script>
    ...
    var latLongList = {{=XML(lat_long_list)}}
    ...
</script>

Upvotes: 4

Related Questions