gpt4 book ai didi

javascript - JavaScript HTML 谷歌图表

转载 作者:行者123 更新时间:2023-11-27 23:46:09 25 4
gpt4 key购买 nike

我有一个 json,其中包含每个服务器的名称和 3 个值:内存、负载和 cpu。

[
{
"server": "Server1",
"Load": "0.04",
"Mem": "64.46",
"Idle": "97.00"
},
{
"server": "Server2",
"Load": "0.01",
"Mem": "64.79",
"Idle": "97.49"
}
]

我在尝试动态创建 Google 图表时遇到一些问题。看起来 Javascript 无法使用循环变量“i”创建变量。请参阅下面的代码:

var obj = JSON.parse(jsonData);

for (i in obj)
{

var data_table[i] = new google.visualization.DataTable();

data_table[i].addColumn('string', 'Label');
data_table[i].addColumn('number', 'Value');

var server = obj[i].server;
var Load = parseFloat(obj[i].Load);
var Mem = parseFloat(obj[i].Mem);
var Idle = parseFloat(obj[i].Idle);
data_table[i].addRow([server, Load]);
data_table[i].addRow([server, Mem]);
data_table[i].addRow([server, Idle]);
var options = {width: 1500, height: 1000, redFrom: 90, redTo: 100, yellowFrom:75, yellowTo: 90, minorTicks: 5};
var chart[i] = new google.visualization.Gauge(document.getElementById('chart_div'+ i +));
chart[i].draw(data_table+i+, options); ' );

$('body').append('<div id="div'+ i +'" />')
}

我想动态创建图表来控制这些图表稍后在 javascript/html 中,而且最重要的是因为我的 json 有点大,所以我想避免必须逐个创建每个图表,或者必须将每个服务器的 json 分开。任何帮助将不胜感激。 ;-)

最佳答案

像这样尝试一下...

// load json
var obj = JSON.parse(jsonData);

// define arrays to store data and charts
var data_tables = [];
var google_charts = [];

// this is the div that will store all of the charts
var chart_area;
chart_area = document.getElementById('chart_div');

// set the chart options
var chart_options;
chart_options = {
width: 1500,
height: 1000,
redFrom: 90,
redTo: 100,
yellowFrom: 75,
yellowTo: 90,
minorTicks: 5
};

// process json array -- fyi: use 'in' keyword for object keys
for (var i = 0; i < obj.length; i++) {
var chart_container; // chart container for this json instance
var data_table; // data table for this json instance
var google_chart; // google chart for this json instance

// load data table
data_table = new google.visualization.DataTable();
data_table.addColumn('string', 'Label');
data_table.addColumn('number', 'Value');
data_table.addRow([obj[i].server, parseFloat(obj[i].Load)]);
data_table.addRow([obj[i].server, parseFloat(obj[i].Mem)]);
data_table.addRow([obj[i].server, parseFloat(obj[i].Idle)]);

// save it to the array
data_tables.push(data_table);

// create the container for this chart
chart_container = document.createElement('DIV');
chart_area.appendChild(chart_container);

// create -- save -- draw the chart
google_chart = new google.visualization.Gauge(chart_container);
google_charts.push(google_chart);
google_chart.draw(data_table, chart_options);
}

// access the charts / data later using arrays --> data_tables and google_charts

关于javascript - JavaScript HTML 谷歌图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com