json not working in javascript in bottle framework

♀尐吖头ヾ 提交于 2019-12-24 19:25:19

问题


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?


回答1:


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}};


来源:https://stackoverflow.com/questions/14157324/json-not-working-in-javascript-in-bottle-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!