[英]Unexpected token { in JSON while passing data from flask to javascript
[英]Passing JSON data from Flask to JavaScript
我正在尝试将 JSON 数据从 flask 传递到 JavaScript。
我尝试的代码来自:
以下步骤是我所做的:
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)
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 }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.