我是网络开发的新手,我想要做的是在我的代码中的Google Chart
函数中绘制drawChart()
。
为了绘制图表,我需要传递一些数据,然后从后端的数据库中获取数据(使用Python),并在下面的GetData()
函数中请求它。
我成功地孤立地完成了这两项任务,但我不确定如何在不失去模块性的情况下将它们放在一起。
换句话说,在功能GetData()
中,如何将ret
传递给drawChart()
?
function GetData()
{
// code for IE7+, Firefox, Chrome, Opera, Safari
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
var ret;
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
ret = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","/submit222", true);
xmlhttp.send();
return ret;
}
function drawChart()
{
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Number of Requests');
var myData = GetData();
for(var i=0; i<5; i++) {
data.addRows([
new Array(new Date(myData[i][0]), Number(myData[i][1]))
]);
}
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true,
};
chart.draw(data, options);
}
</script>
</head>
<body onload="GetData()">
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
"""
答案 0 :(得分:1)
由于请求是异步的,因此您必须重新调整程序的工作方式:
function getData(callback) {
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else { // code for IE6, IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "/submit222", true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
}
function drawChart(myData) {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Number of Requests');
var rows = new Array(5);
for (var i = 0; i < rows.length; i++) {
row[i] = [ new Date(myData[i][0]), myData[i][1] ];
}
data.addRows(rows);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true,
};
chart.draw(data, options);
}
</script>
</head>
<body onload="getData(drawChart)">
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>