我正在本地运行flask应用,我的目标是将字典从python传递到Javascript。我目前能够将字典作为json文件存储在本地文件夹中,但是我的ajax请求似乎无法访问本地json。为什么这不起作用,并且有一个flask模块可以让我将python字典传递给本地javascript?
# app.py
dictionary_a = {
"a": {
"b": {
"function_handler": c,
"defaults": {'d':e, 'f':g},
},
"h": {
"function_handler": i,
"defaults": {'d':l},
},
},
}
def dumper(obj):
try:
return obj.toJSON()
except:
return obj.__dict__
@app.route('/')
def index():
jsonn = json.dumps(dictionary_a, default=dumper, indent=2)
with open('data.json', 'w') as json_file:
json.dump(jsonn, json_file)
return render_template('home.html')
这是我的python代码,
# code.js
$.getJSON("../../data.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
这是JavaScript代码
文件夹结构是
>project
-app.py
>static
>js
-code.js
-data.json
错误消息:获取http://localhost:5000/data.json 404(找不到)
已解决:
# code.js
var script = document.currentScript;
var fullUrl = script.src;
这些行允许获取code.js的路径
var jsonUrl = fullUrl.replace("code.js", "data.json") // hard coded jsonUrl
$.getJSON(jsonUrl, function(from_to_conversions) {
console.log(from_to_conversions)
});
我将json文件转储到static / js文件夹中,以使其正常工作
您是否试图在HTML文件中呈现python字典?您应该考虑使用Jinja。
如果在响应中添加字典,则HTML页面as of flask 1.1将以JSON的形式接收它。
# app.py
dictionary_a = {
"a": {
"b": {
"function_handler": c,
"defaults": {'d':e, 'f':g},
},
"h": {
"function_handler": i,
"defaults": {'d':l},
},
},
}
@app.route('/')
def index():
jsonn = dictionary_a
return render_template('home.html', jsonn=jsonn)
然后您可以使用Jinja在html页面中处理它。
您可以遍历其元素,添加if语句等...
您的home.html应该看起来像这样:
<html>
...
<body>
...
{{jsonn}}
...
</body>
...
</html>
您也可以将其直接传递给您的JavaScript代码,并在需要时像json一样处理它
<script>
const jsonn = `{{jsonn | safe}}`
</script>