2013-08-26 52 views
2

您好我嘗試使用谷歌圖表來顯示趨勢線,基於從Java文件生成的一些數據。 這裏是我的代碼Google chart:如何將數據表從Java文件傳遞到JavaScript

public void resolveEvolution() { 
     this.evolution = new ArrayList<Long>(); 
     this.evolutionTime = new ArrayList<String>(); 
     Calendar first = Calendar.getInstance(); 
     first.setTime(this.start); 
     first.set(Calendar.DAY_OF_MONTH, 1); 
     Calendar last = Calendar.getInstance(); 
     last.setTime(this.end); 

     int i = 0; 

     this.dt = DataTable.create(); 
     dt.addColumn(ColumnType.NUMBER, "Time"); 
     dt.addColumn(ColumnType.NUMBER, "Utilisation"); 
     dt.addRow(); 
     while (first.before(last)) { 
      Calendar endMonth = Calendar.getInstance(); 
      endMonth.setTime(first.getTime()); 
      endMonth.add(Calendar.MONTH, 1); 
      endMonth.add(Calendar.DAY_OF_MONTH, -1); 

      this.evolution 
        .add(actionQueries.countByComponent(this.selectedComponent, 
          first.getTime(), endMonth.getTime())); 
      this.evolutionTime.add(first.get(Calendar.MONTH) + "/" 
        + first.get(Calendar.YEAR)); 
      dt.addRow(); 
      dt.setValue(i, 0, i); 
      dt.setValue(i, 1, 
        actionQueries.countByComponent(this.selectedComponent, 
          first.getTime(), endMonth.getTime())); 
      i++; 
      first.add(Calendar.MONTH, 1); 
     } 
    } 

    public DataTable getDt() { 
     System.out.println(this.dt); 
     return this.dt; 
    } 

一部分這裏是我的XHTML:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:f="http://java.sun.com/jsf/core"> 
    <head>  
<script type="text/javascript" src="https://www.google.com/jsapi"></script>  
<script type="text/javascript">  
    google.load("visualization", "1", {packages:["corechart"]});  
    google.setOnLoadCallback(drawChart);  
    function drawChart() {   
     var data = new google.visualization.DataTable(); 
     data = "#{globalComponentsManager.dt}"; 
     var options = {   
      title: 'Test', 
          trendlines: { 0: {} } 

     };  
     var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); 

     chart.draw(data, options);  
    }  
    </script> 
</head> 
<body> 
     <div id="chart_div" style="width: 900px; height: 500px;"></div> 
</body> 

</html> 

很顯然,這是行不通的。那麼如何將數據表從java傳遞到JavaScript?我正在使用JSF框架。謝謝。

回答

3

嗯,我終於找到了解決方案。我希望它能幫助未來遇到同樣困難的人們。 JSF可以將一些參數從Java傳遞給Web頁面,包括JSF頁面中的JavaScript。 所以我在Java文件中使用StringBuilder來構建行的字符串,如[[1,2],[5,9],[4,3]]。然後我將這個String傳遞給JavaScript,Google圖表的代碼,就像data.addRows(#{stastics.rows})。對於谷歌圖表代碼的其他部分,只需參考谷歌圖表文件。它運行良好,我最終得到了我需要的圖表。

相關問題