【发布时间】:2018-09-07 08:42:09
【问题描述】:
有人可以帮我理解如何通过 HTML 将视图中的两个变量传递给 javascript 吗? 当我只传递动态(从 db 获取)json 格式的数据时,一切正常,但我还需要将另一个静态整数值一直传递给 JS 文件。 当我更改视图 .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 文件中的烧瓶视图 .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”,但我认为这无关紧要(如果查看所有内容有帮助,请告诉我)。
非常感谢任何帮助。谢谢!
【问题讨论】:
标签: javascript python-3.x flask jinja2