我想知道是否有办法将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字典? 这样做是个好主意吗?因为它是安全和最佳实践吗?
答案 0 :(得分:1)
您应该使用AJAX方法让瓶子应用程序以JSON格式(或XML,如果您对此感到满意)返回数据,然后可以通过JavaScript函数操作返回的值。
答案 1 :(得分:0)
我想出来了,这是一个例子:
将字典传递给模板,如下所示:
@bottle.route('/')
def index():
data = [{"user":"Bernard"}]
return bottle.template("index", data=data)
并在模板中只读它:
console.log("{{data['user']}}")
另外,要像Josh English所说的那样用javascript调用Ajax,创建一个POST函数并将字典作为JSON发送,如下所示:
@bottle.route('/get-user-info', method="POST")
def get_user_data():
data = [{"user":"Bernard"}]
retun json.dumps(data)
并在javascript中调用Ajax,以获取JSON文件:
// getting the data
var result = $.ajax({
url: "/get-user-info",
type: 'POST',
dataType: 'json',
contentType: "application/json",
async: true,
});
希望帮助那些有同样问题的人。