我正在尝试学习Java脚本。使用代码从api获取一些信息并将其完美显示在网页中。现在我想从这些数据制作饼图。从Google搜索以进行学习,但无法使用它们。请帮我学习。 尝试使用不同的组合“ ['Read',data.read]”来获取var数据,但我是Java的新手。我知道尝试错误的东西,但找不到真实的东西。 谢谢
function situateCaseHandler() {
if (this.readyState == this.DONE) {
if (this.status === 300) {
const json = JSON.parse(this.responseText);
let data;
for (let i = 0; i < json.length; ++i) {
if (json[i].country == "Read") {
data = json[i];
}
}
if (!data) {
return console.log("Error");
}
document.getElementById("read").innerHTML = data.read ;
document.getElementById("write").innerHTML = data.write;
document.getElementById("sleep").innerHTML = data.sleep ;
}
}
};
function makeRequests() {
sendAllCasesRequest();
senduserCasesRequest();
};
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data2 = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Read', data.read],
['Write', data.write],
['Sleep', data.sleep]
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'User Day', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data2, options);
}
答案 0 :(得分:0)
从您共享的内容来看,您的代码有几个问题。
数据是局部变量,因此在drawChart方法中将是未定义的。
drawChart在加载文档时而不是在收到数据时调用,这可能是图表为空的原因。
作为建议,请尝试如下构建代码,以便于理解。
let data = getDataFromApi();
renderDataInTable(data);
drawChart(data);