喵-见缝插针 2014-08-13 00:30 采纳率: 0%
浏览 142

如何传递并使index.html能够通过Flask和Jinja 2接收新值?

我花了两天时间还是没搞清楚这个问题。

index()中的打印值每次都不同,而且一旦它通过rendertemplate('index.html', carvalue=value)转到html,它就接收不到新的不同值了。console.log(y)只能打印出第一个接收到的值,之后传递的其他值就接收不到了。请告诉我如何传递并使index.html能够通过Flask和Jinja 2接收新值?


更新:
def get_data():
    df = sqlio.read_sql(qry1, conn)
    value = df['count'][0]
    return value

@app.route('/get_data', methods=['GET','POST'])
def get_data_route():
    value = get_data()
    return value

@app.route('/get_car_value', methods=['GET'])
def get_car_value():
    data = "{ car_value: %s }" % get_data_route()
    return data, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(
        port=8000,
        host='0.0.0.0'
    )

以及:

$(function() {
    var chart;
    $('#car_id').highcharts({
        chart: {
            type: 'spline',
            animation: Highcharts.svg, // don't animate in old IE
            marginRight: 10,
            events: {
                load: function() {
                    var series = this.series[0];
                    setInterval(function() {
                        var x = (new Date()).getTime();
                        $.ajax({
                            type: "GET",
                            url: "/get_car_value",
                            success: function(data) {
                                var y = data.car_value;
                                console.log(y)
                                series.addPoint([x, y], true, true);
                            }
                       });
                    }, 5000);
                }
            }
        },

还是没用...... console.log任何东西都不输出。

  • 写回答

1条回答 默认 最新

  • weixin_33739541 2014-08-13 00:36
    关注

    Since you always access the same URL with AJAX, chances are good it is being cached. Try adding this at the top of the Flask controller responsible for the data AJAX:

    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    

    Alternately, you can change your URL to:

    url: "/?" + new Date().getTime(),
    

    so it's impossible to cache (since it will be different each time).

    EDIT: I just noticed, you're setting the value of y in the template, which has no relevance to the AJAX call. To refresh that value, you would have to reload the page, AJAX is useless as it stands, since it fetches some data and then ignores it.

    url: '/get_car_value',
    success: function(data) {
      var y = data.car_value;
      console.log(y)
      series.addPoint([x, y], true, true);
    }
    

    and make a new controller:

    @app.route('/get_car_value', methods=['GET'])
    def get_car_value():
        import json
        data = json.dumps({ car_value: get_data_route() })
        return data, 200, {'Content-Type': 'application/json; charset=utf-8'}
    

    (you could use the existing get_data_route controller, but I like a consistent API, and always using JSON when transfering data with AJAX is pretty useful).

    EDIT: JSON brain fart.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器