下面的 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>
查詢代碼:
<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)
uj5u.com熱心網友回復:
通過 ajax 定期查詢和顯示 plotly 資料的簡單示例。
我創建了另一個以 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/349917.html
標籤:javascript 查询 阿贾克斯 烧瓶
