How to pass data from python to javascript in web2py

I see some relevant messages in my request.

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

I know it can be done with json, but I don't understand how to implement it. In the default controller for web2py, I return a dictionary that 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 a java script I want to loop through a list of dictionaries and mark points on google maps.

I can not tell

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

      

It fails. An alternative for this is to write the list to xml and from javascript reading the file, but I don't want to achieve that as writing to file doesn't work. Let me know how this can be achieved.

+3


source to share


1 answer


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

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

      



In view:

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

      

+3


source







All Articles