有人可以帮我理解如何通过 HTML 将两个变量从我的 View 传递到 javascript 吗? 当我只传递动态(从数据库获取)json 格式的数据时,一切正常,但我还需要将另一个静态整数值一直传递到 JS 文件。 当我更改 View .py 文件时:
response = make_response(render_template('live-data.html', data=json.dumps(data)))
到
response = make_response(render_template('live-data.html', data=json.dumps(data), bpm=777))
然后我将 {{bpm}} 添加到 live-data.html。最后在 JS 文件中我更改了函数的输入参数
success: function(point) {
到
success: function(point, bpm) {
比“休息”之前正在工作的东西。 :/如何从 JS 文件中的 Flask View .py 获取动态数据元组和静态整数文件?
这就是我所拥有的,并且在我进行更改以从 JS 文件中的 .py 接收“bpm”值之前它工作正常。
.py 文件:
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/live-data')
def live_data():
# Create an array and echo it as JSON
cur = mysql.connection.cursor()
cur.execute('''SELECT time, value FROM data ORDER BY id DESC LIMIT 1''')
rv = cur.fetchall()
u_time = time.mktime(rv[0]['time'].timetuple())
value = rv[0]['value']
#time in unix form
data = [u_time * 1000, value]
response = make_response(render_template('live-data.html', data=json.dumps(data)))
response.content_type = 'application/json'
return response
index.html:
<div class="container-fluid">
<div class="row">
<div class="container-fluid" id="data-container"></div>
</div>
</div>
live-data.html:
{{ data }}
在 JavaScript 文件中:
var chart;
function requestData() {
$.ajax({
url: '/live-data',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// title
// chart.setTitle(null, {text: "Beats per minute - " + bpm});
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
还有更多的 js 代码填充了 index.html 上的“data-container”,但我认为它在这里无关紧要(如果看到所有这些代码会有帮助,请告诉我)。
非常感谢任何帮助。谢谢!
最佳答案
所以你现在采取的方法非常乏味。你向flask发送一个AJAX请求,flask会查找一些数据,然后将数据渲染成文本文件/html文件,然后将请求调整为json类型,然后才返回到浏览器.
Flask 已经内置了处理 json 的功能,因此您无需执行所有这些步骤。
js 中的 success
函数应该只接受一个参数,响应 flask 已经给了你。
var chart;
function requestData() {
$.ajax({
url: '/live-data',
success: function(response) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(response.data, true, shift);
// title
// chart.setTitle(null, {text: "Beats per minute - " + response.bpm});
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
您使用flask做出的响应可以使用flask中的jsonify函数来完成。该函数将字典转换为 JSON。
from flask import jsonify
@app.route('/live-data')
def live_data():
cur = mysql.connection.cursor()
cur.execute('''SELECT time, value FROM data ORDER BY id DESC LIMIT 1''')
rv = cur.fetchall()
u_time = time.mktime(rv[0]['time'].timetuple())
value = rv[0]['value']
#time in unix form
data = [u_time * 1000, value]
return jsonify({'data': data, 'bpm': 777})
关于javascript - 在 Flask 中使用 make_response 将两个变量传递给 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52218695/