[英]Unexpected token { in JSON while passing data from flask to javascript
I am trying to pass simple data from flask to javascript file I am following this answer Passing a JSON object from Flask to JavaScript 我正在尝试将简单的数据从Flask传递到javascript文件,我正在按照此答案将JSON对象从Flask传递到JavaScript
But i got Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse () 但是我遇到了Uncaught SyntaxError:意外的令牌{在JSON.parse()位置1的JSON中
var user = JSON.parse('{{ data | tojson}}');
var grade=user.grade;
console.log(grade);
my python file have code 我的python文件有代码
@app.route("/quiz/0")
def quizFirst():
data={"grade":"0"}
return render_template('quiz.html',data=data)
the token { is not recognizable by javascript in js file, Any idea what i am missing. 令牌{无法被js文件中的javascript识别,任何想法我都缺少。
It works for me. 这个对我有用。 This JavaScript needs to be inside quiz.html
. 该JavaScript必须位于quiz.html
。 The reason is that Flask will process quiz.html
and replace {{ data | tojson }}
原因是Flask将处理quiz.html
并替换{{ data | tojson }}
{{ data | tojson }}
with the data provided in render_template
. {{ data | tojson }}
以及render_template
提供的数据。 However, it won't process your static JS file. 但是,它不会处理您的静态JS文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>sotest</title>
</head>
<body>
Hello World!
<script>
var user = JSON.parse('{{ data | tojson}}');
var grade=user.grade;
console.log(grade);
</script>
</body>
</html>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/quiz/0")
def quizFirst():
data={"grade":"0"}
return render_template('quiz.html',data=data)
if __name__ == "__main__":
app.run(debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.