1

我有一個json與每個服務器的名稱和3個值:內存,負載和CPU。Javsascript HTML谷歌圖表

[ 
{ 
    "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。 任何幫助將非常感激。 ;-)

回答

1

嘗試像這樣...

// 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 
+0

感謝很多的WhiteHat。 – lucasheringer

+0

乾杯!很高興幫助,你會接受我的回答嗎? – WhiteHat