【问题标题】:Passing ajax-requested data into Python function将 ajax 请求的数据传递给 Python 函数
【发布时间】:2023-03-17 11:50:01
【问题描述】:

下面的 Flask 应用程序使 Ajax 无限期地调用后端索引函数,该函数查询数据库并将结果注入模板。

我希望,在 Ajax 完成后,注入的数据将被刷新,从而更新绘图,但事实并非如此。

如何以将注入的数据刷新到“index.html”中的方式更新 Ajax(因此更新使用该数据的绘图)?

感谢您的帮助!

HTML 代码:

<div class="card-body">
    <div  class="chart-area">
       <div id = 'load' class = 'chart' style = 'height:100%'></div> <!--This is where chart appears -->
     </div>
   </div>

JQuery 代码:

<script> 
    $(document).ready(function(){

        function ajaxCall(){

            $.ajax({
                async: false,
                type: 'POST',
                url: '/',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                success: function (data) {
                  ??? perhaps something here???
                    }
            });

        }

    setInterval(ajaxCall, 2000); // repeatedly calls ajaxCall()

    var graphs = {{graphJSON | safe}}; // saves injected data to variable

    Plotly.plot('load',graphs,{}); // passes saved variable to Python function for plotting which then appears in div with 'load' id above.

    });
</script>

烧瓶代码:

from flask import render_template, Blueprint,  
from App.functions.reddit_streamer import AWS_RDB
import json
import plotly
import plotly.express as px



core = Blueprint('core', __name__)



@core.route('/', methods = ['GET', 'POST'])
def index():

    db = AWS_RDB()

    df = db.query_half_hour()

    fig = px.line(df.loc[1:,:], x = 'date' , y = '# of comments')

    graphJSON = json.dumps(fig, cls = plotly.utils.PlotlyJSONEncoder)

    return render_template('index.html', graphJSON = graphJSON)

【问题讨论】:

    标签: javascript jquery ajax flask


    【解决方案1】:

    通过 ajax 定期查询和显示数据的简单示例。

    我创建了另一个以 JSON 格式提供数据的路由。然后我使用Fetch API 来查询数据,然后用它来更新图形。 jQuery 的实现也是可以想象的。

    from flask import Flask
    from flask import make_response, render_template
    import json, random
    import pandas as pd
    import plotly
    import plotly.express as px
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/data')
    def data():
        df = pd.DataFrame({
            'Year': ['2012', '2014', '2016', '2018', '2020', '2022'],
            'Amount': [random.randint(0, 10) for _ in range(6)],
        })
    
        fig = px.line(df, x='Year', y='Amount')
        dat = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    
        resp = make_response(dat)
        resp.mimetype = 'application/json'
        return resp
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <div id="chart" class="chart"></div>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
        <script type="text/javascript">
          (() => {
            const update = () => {
              fetch('/data')
                .then(resp => resp.json())
                .then(data => Plotly.react('chart', data, {}));
            };
            update();
            setInterval(update, 2000);
          })();
        </script>
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2011-06-19
      • 2016-07-19
      • 2012-02-12
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多