在这里的一个项目中,我使用Flask从API中获取值。然后使用chart.js将其添加到图表中
我让它在某种程度上发挥了作用,我面临的问题是,我用来向图表中添加值的变量,但它不会改变变量,只要API中的值发生变化,我就会添加到图表中
意思是: 售价:10.3 销售价格更改为10.4 售价:10.3<;——它不会更改为10.4
以下是我的python代码:
@app.route('/product/<product>')
def productPage(product):
price = []
data = requests.get(
'https://api.hypixel.net/skyblock/bazaar?key=').json()
sell = data['products'][product]['sell_summary']
for x in sell:
price.append(x['pricePerUnit'])
currentSell = data['products'][product]['sell_summary'][0]['pricePerUnit']
return render_template('product.html', product=product, price=price, currentSell=currentSell)
@app.route('/graph_update/<product>', methods=['GET', 'POST'])
def graph_update(product):
data = requests.get(
'https://api.hypixel.net/skyblock/bazaar?key=').json()
currentSell = data['products'][product]['sell_summary'][0]['pricePerUnit']
return jsonify('', render_template('graph_update.html', currentSell=currentSell))
这里是HTML/JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="container" style="position: relative; height: 40vh; width: 80vw">
<canvas style="width: 25%" id="myChart"></canvas>
</div>
<input
type="button"
value="add data"
style="margin-top: 25%"
onclick="addData()"
/>
<h1 style="padding-top: 25%">{{product}}</h1>
{% for sell in price %}
<p id="sellprice">{{ sell }}</p>
{% endfor %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script>
var sellprice = JSON.parse("{{ currentSell | tojson | safe }}");
var product = "{{ product }}";
let myChart = document.getElementById("myChart").getContext("2d");
let priceChart = new Chart(myChart, {
type: "line", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: [],
datasets: [
{
label: "Sell Price",
},
],
},
options: {},
});
var getData = function () {
$.ajax({
url: "/graph_update/" + product,
success: function (data) {
// process your data to pull out what you plan to use to update the chart
// e.g. new label and a new data point
// add new label and data point to chart's underlying data structures
var sellprice = JSON.parse("{{ currentSell | tojson | safe }}");
priceChart.data.labels.push(sellprice);
priceChart.data.datasets[0].data.push(sellprice);
// re-render the chart
priceChart.update();
},
});
};
// get new data every 3 seconds
setInterval(getData, 10000);
</script>
谢谢
问题在于,端点
/graph_update/<product>
处的python代码应该以JSON的形式返回数据,目前它正在执行以下操作:您需要返回类似的内容
相关问题 更多 >
编程相关推荐