在Flask中使用make_response将两个变量传递给javascript

时间:2018-09-07 08:42:09

标签: javascript python-3.x flask jinja2

有人可以帮助我了解如何通过HTML将视图中的两个变量传递给javascript吗? 当我仅传递动态(取自db的)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文件中的烧瓶视图.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上填充“数据容器”,但是我认为这无关紧要(请让我知道是否所有内容都对您有帮助)。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

因此,您现在采用的方法非常繁琐。您正在向烧瓶发送AJAX请求,烧瓶然后查找一些数据,然后将数据呈现为文本文件/ html文件,然后将请求调整为json类型,然后才返回到浏览器

Flask已经具有处理json的内置功能,因此您无需执行所有这些步骤。

您在js中的success函数应该只接受一个参数,响应瓶已经给出了。

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中的jsonify函数来完成使用flask做出的响应。此函数将字典转换为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})