使用外部js文件从flask获取json

时间:2021-01-22 21:00:50

标签: javascript python html

我有一个烧瓶服务器吐出从 Pandas 数据帧转换的 json 数据,如下所示:

[{'name': 'FBtr0075557',
  'score': '164.00'},
 {'name': 'FBtr0075557',
  'score': '162.00'}]

我用来将数据帧转换为 json 并在 Flask 中提供的 python 代码是:

result = df.to_json(orient="records")
parsed = json.loads(result)
return render_template('mirtar.html', targets=json.dumps(parsed))

当我使用内部 javascript 时,数据被解析没有任何错误:

<script type="text/javascript">
const targets = {{ targets|tojson }};
const entries = JSON.parse(targets);
console.log(entries);
</script>

但是,当我尝试使用外部 JS 脚本执行相同操作时,出现错误

Uncaught SyntaxError: Unexpected token { in JSON at position

据我所知,外部 javascript 中的

const targets = {{ targets|tojson }};
行与内部 javascript 中的行为方式不同,并且该行的第一个 '{' 被视为错误。 我敢肯定这是一个非常基本的问题,必须有一种简单的方法可以解决,但我肯定错过了。

1 个答案:

答案 0 :(得分:0)

Jinja 语法仅在flask html 模板中解析,而不是在外部加载的JS 资产中解析:因为它是python 应用程序进行解析,并且在部署环境中,您通常会使用nginx 等网络服务器提供静态资产。

对此进行排序的最快方法可能是使用 this method,在这种情况下,您可以使用 HTML 元素中的数据属性。这感谢您将数据作为 render_template 的参数传递给模板,因此数据在页面加载时存在于模板中。

在你的情况下,这可能看起来像

<!-- a hidden tag -->
<input type='hidden' id='targetid' data-thetargets='{{ targets|tojson }}' />

然后在您的 javascript 中加载它:

var targets = JSON.parse(document.getElementById("targetid").dataset.thetargets);