[英]Calling external Chartjs chart from a javascript file into HTML in Flask
我正在創建一個網頁。 我希望在此網頁上加載Chartjs文件。 為了保持我的結構整潔。 我想將Chart對象放入外部“ scripts.js”文件中,並以HTML腳本的形式調用它。 我正在使用Flask創建網站。
當我在HTML中包含所有代碼時,它工作正常,但似乎不讓我導入JS腳本。 請幫我一個人。 謝謝。
嘗試:“ scripts.js”:
function linechart() {
const LINECHART = document.getElementById("lineChart")
let lineChart = new Chart (LINECHART, {
type: 'line',
data: {
labels: {{ data_date|tojson|safe }},
datasets: [{
responsive: false,
label: "Share Price",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: {{ data_close|tojson|safe }},
spanGaps: true,
}]
},
// orientate the labels to be 90 degrees on x-axis
// credit: https://stackoverflow.com/questions/35022830/chart-js-change-label-orientation-on-x-axis-for-line-charts
options: {
scales: {
xAxes: [{
ticks: {
autoSkip: true,
maxTicksLimit: 6,
autoSkipPadding: 2,
maxRotation: 0,
minRotation: 0
}
}]
}
}
}); // end of lineChart
}
HTML:
<head>
<script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>
<canvas id="lineChart" width="20" height="20"></canvas>
<script>
linechart()
</script>
如果代碼在HTML文件中運行良好,則問題必須出在資源路徑上。 您是否已從瀏覽器確認正在加載script.js
文件?
您的html是Flask轉換為實際html的模板代碼。
<script src="{{ url_for('static', filename='scripts.js') }}"></script>
在瀏覽器中打開頁面,然后使用“查看源代碼”查看最終的html。 {{ }}
內部的部分將被替換。
實際的html應該看起來像這樣。
<script src="/static/scripts.js"></script>
生成的src
網址很可能丟失或不正確,這意味着您的瀏覽器將無法加載和執行javascript文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.