【发布时间】:2017-04-14 16:24:36
【问题描述】:
我想知道是否有办法将 python 字典传递给 javascript?
好的,我正在使用bottle 来创建一个 Web 框架,我的设置是这样的:
在 runTheApp.py 我有:
# importing general packages
import bottle
@bottle.route('/')
def index():
return bottle.template("index")
@bottle.route('/static/<filename>')
def server_static(filename):
return bottle.static_file(filename, root="./js")
if __name__ == "__main__":
bottle.run(host="localhost",port=8080,debug=True,reloader=True)
我想要访问的python字典在myData.py中:
def get_data():
return {"Name":"James","City":"KL"}
我可以从 index.tpl 访问 python:
<!DOCTYPE html>
<html lang="en-us" xml:lang="en-us">
%import myData
%data = myData.get_data()
<head>
<title>Home</title>
</head>
<body>
<p id="greeting"> Hi {{data["Name"]}} from {{data["City"]}} </p>
</body>
<script type="text/javascript" src="/static/changer.js"></script>
</html>
但我想从 changer.js 访问它,我有:
var greeting_p = document.getElementById("greeting");
var wishing_p = document.createTextNode("hope you are doign well.");
greeting_p.appendChild(wishing_p);
如何从 javascript 中获取 python 字典? 这样做是个好主意吗?比如它是安全的最佳实践吗?
【问题讨论】:
标签: javascript html python-2.7 bottle