将烧瓶中的数据传递到javascript时,JSON中出现意外令牌{ [英] Unexpected token { in JSON while passing data from flask to javascript
问题描述
我正在尝试将简单数据从烧瓶传递到javascript文件我正在关注这个答案将JSON对象从Flask传递到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
但是我收到了Uncaught SyntaxError:意外令牌{在JSON中的位置1在JSON.parse()
But i got Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse ()
var user = JSON.parse('{{ data | tojson}}');
var grade=user.grade;
console.log(grade);
我的python文件具有代码
my python file have code
@app.route("/quiz/0")
def quizFirst():
data={"grade":"0"}
return render_template('quiz.html',data=data)
令牌{无法被js文件中的javascript识别,任何想法我都缺少.
the token { is not recognizable by javascript in js file, Any idea what i am missing.
推荐答案
它对我有用.该JavaScript必须位于 quiz.html
中.原因是Flask将处理 quiz.html
并替换 {{data |tojson}}
和 render_template
中提供的数据.但是,它不会处理您的静态JS文件.
It works for me. This JavaScript needs to be inside quiz.html
. The reason is that Flask will process quiz.html
and replace {{ data | tojson }}
with the data provided in render_template
. However, it won't process your static JS file.
<!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>
app.py
#!/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)
这篇关于将烧瓶中的数据传递到javascript时,JSON中出现意外令牌{的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!