通过AJAX在一个单独的JS文件中将变量从Flask (Python)传递到Javascript &



我正处于学习阶段,所以请耐心等待。我一直试图得到答案,但往往是type="POST">

这是我的app.py.

@app.route("/dashboard", methods=["GET","POST"]);
def dashboard():
yearCount = #Sample list of dict data
return render_template("dashboard.html", yearCount=yearCount)

(编辑)我如何从上面得到yearCount并通过AJAX将其传递给javascript ?当dashboard.html呈现时,将加载yearCount。

这是我的js
$.ajax({
url: '/dashboard',
type: "GET",
// data: "How do I get the data yearCount from /dashboard?",
success: function() {
alert(this.url);
}
});
我真的很感谢你的帮助!整个星期我都在拼命寻找答案。

在呈现过程中从模板传输变量:
你可以通过jinja过滤器tojson将变量作为json传递。如果你需要在你的模板之外的变量,你必须把它作为参数传递。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
const yearCount = {{ yearCount | tojson }};
console.log(yearCount);
</script>
</body>
</html>

当页面已经在浏览器中显示时加载数据:
如果您希望在模板呈现后再次接收变量,那么ajax是正确的选择。

from flask import jsonify
@app.route('/count')
def count():
yearCount = # your dict data here.
return jsonify(yearCount)

在您的示例代码中,您正在使用jQuery库。然而,在fetch api的帮助下实现也是可能的。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Load the jQuery library. -->
<script 
src="https://code.jquery.com/jquery-3.6.0.min.js" 
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
crossorigin="anonymous"></script>
<!-- Use the jQuery library to load data with ajax. -->
<script type="text/javascript">
// jQuery ajax
$.ajax({
url: '/count'
}).done((data) => {
console.log(data);
});
</script>

<!-- The fetch api does not require any additional library. -->
<script type="text/javascript">
// fetch api
fetch('/count')
.then(resp => resp.json())
.then(data => console.log(data));
</script>
</body>
</html>