我正在尝试从另一个php文件中获取变量并在图表中设置它。可悲的是,图表没有显示任何内容(因为MachineActivityS = 0
的起始值)。当我删除var MachineActivityS = 0;
时,它会说:MachineActivityS isn't defined
。如果我在AJAX代码中设置图表的所有内容,它将不会显示图表。
您可以在下面找到代码:
<script type="text/javascript">
var MachineActivityS = 0;
$.ajax
({
url: 'MachineActivityS.php',
type: 'get',
success: function(response)
{
MachineActivityS = response;
},
});
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var amountOfProducts = Math.floor(((hours * 60) + minutes) * 1.8);
var barChartData =
{
labels : ["Activity in minutes","Number of products"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [minutes + (hours * 60), amountOfProducts]
}
]
}
window.onload = function()
{
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : false,
animation: false
});
}
</script>
如何获取该文件中的值并将其设置在我的图表中?
答案 0 :(得分:1)
您在回调中定义了新的MachineActivityS
。所以改变
success: function(response) {
var MachineActivityS = response;
}
到此:
success: function(response) {
MachineActivityS = response;
}
此外,由于您的AJAX调用是异步运行的,因此您也希望将使用MachineActivityS
的所有内容移动到该回调中。
success: function(MachineActivityS) {
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var amountOfProducts = Math.floor(((hours * 60) + minutes) * 1.8);
...
}
修改:要确保在页面加载并且您的AJAX调用返回后绘制图表,请将$.ajax
调用移至window.onload
事件处理程序:
window.onload = function() {
$.ajax({
...,
success: function(MachineActivityS) {
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var amountOfProducts = Math.floor(((hours * 60) + minutes) * 1.8);
var barChartData = ...;
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : false,
animation: false
});
}
});
};