javascript - 将 JSON 数据从 Flask 传递到 JavaScript
问题描述
我正在尝试将 JSON 数据从烧瓶传递到 JavaScript。
我尝试的代码来自:
以下步骤是我所做的:
- 我首先在 Python 中从 postgreSQL 获取数据
- 我将数据格式从 DataFrame 转换为 JSON
def to_json2(df,orient='split'):
df_json = df.to_json(orient = orient, force_ascii = False)
return json.loads(df_json)
def to_fronrend(data):
return {"data": data}
json2 = to_json2(df)
json2 = to_fronrend(json2)
- 我修改了@Ilya V. Schurov 的代码
app = Flask(__name__)
@app.route('/')
def hello_world():
data = json2
return render_template("index.html", data = data)
app.run()
这是我的 index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Hello </title>
</head>
<body>
<p>Hello, <span id="username"></span></p>
<script>
var data = JSON.parse('{{ json2 | tojson | safe}}');
document.getElementById('username').innerHTML = data.Name + " " + data.Gatein;
</script>
</body>
</html>
但是,它一直显示错误
TypeError: Object of type Undefined is not JSON serializable
127.0.0.1 - - [18/Dec/2020 22:14:14] "GET / HTTP/1.1" 500 -
网页(http://127.0.0.1:5000/)显示:
Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
我在这个问题上花了将近 2 天的时间,将 json 数据传递给 JavaScript,但仍然不知道如何解决这个问题......有人可以给我一些建议吗?
解决方案
在模板中,您正在使用变量json2
:
{{ json2 | tojson | safe}}
但是,在渲染时,您正在传递变量data
:
return render_template("index.html", data=data)
在您的模板中替换json2
为:data
{{ data | tojson | safe }}
推荐阅读
- angular - Angular2中的异步调用
- python - 如何从 Moloch 获得完整的有效载荷
- c# - 如何修复计算网站中最常见的单词
- accessibility - 具有 NVDA 屏幕阅读器可访问性的 ag-grid
- android - 偏好连接器
- colors - 如何临时或永久更改维基百科页面中的数学公式颜色?
- java - 如何以编程方式创建“.nomedia”文件并将图像存储在其中?
- c# - 从excel C#读取带有长字符串的单元格
- xcode - 如何将 NSTextView 内容输出到文本文件
- javascript - Electron:无法在 BrowserWindow 中隐藏程序图标