[英]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.