我试图从另一个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>
如何获得该文件中的值并在图表中进行设置?
最佳答案
您正在回调中定义新的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
});
}
});
};