【问题标题】:Passing two variables to javascript using make_response in Flask在 Flask 中使用 make_response 将两个变量传递给 javascript
【发布时间】: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


    【解决方案1】:

    因此,您现在采用的方法非常乏味。你正在向flask发送AJAX请求,flask然后查找一些数据,然后将数据渲染为文本文件/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做出的响应可以使用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})
    

    【讨论】:

    • 太棒了,谢谢@Joost!它还要求我将 JS 中的“response.point”更改为“response.data”,但是关于您的方法的其余部分效果很好!感谢您的帮助!
    猜你喜欢
    • 2016-07-08
    • 2022-07-17
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多