简体   繁体   中英

json not working in javascript in bottle framework

I am now totally confused with the usage of data structures in bottle...

Now I am using a Jquery tool ztree to build a tree in my web page.

index.py:

data = [{'name':'1'},
        {'name':'2'}]
return template('index', data) 

But, when I try to get data in my JavaScript code as {{data}} , and then pass it to ztree to build my tree, it shows nothing.

On the other hand, if I pass [{'name':1'},{'name':2}] directly to ztree, a tree is built as expected. So what's the difference between the two?

You are passing in a Python structure, which a Javascript framework won't know anything about. The string representation interpolated into a template may look a lot like a JavaScript structure but there are (many) differences.

Translate it to a structure Javascript can read by using the json module:

import json

# ...
data = json.dumps(data)

then interpolate that into your Javascript code as a (unescaped) variable:

data = {{!data}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM