2014-02-11 132 views
1

我很新的ajax和在Java中繪製圖表。我非常感興趣的是使用ChartJS創建用於網絡報告的動態儀表板。我想問一下如何使用ajax和來自servlet響應的數據填充「圖表標籤」和「數據集」。填充chartjs ajax servlet

我嘗試了一些研究和測試了一些教程關於Ajax和ChartJS,但我似乎無法使它工作..

<html> 
     <head> 
      <title>Bar Chart</title> 
      <script src="../Chart.js"></script> 
      <meta name = "viewport" content = "initial-scale = 1, user-scalable = no"> 
      <style> 
       canvas{ 
       } 
      </style> 
     </head> 
     <body> 
      <canvas id="canvas" height="450" width="600"></canvas> 


     <script> 

      var barChartData = { 
       labels : [,"January","February","March","April","May","June","July"], 
       datasets : [ 
        { 
         fillColor : "rgba(220,220,220,0.5)", 
         strokeColor : "rgba(220,220,220,1)", 
         data : [65,59,90,81,56,55,40] 
        }, 
        { 
         fillColor : "rgba(151,187,205,0.5)", 
         strokeColor : "rgba(151,187,205,1)", 
         data : [28,48,40,19,96,27,100] 
        } 
       ] 

      } 

     var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData); 

     </script> 
     </body> 
    </html> 

回答

1

找到了答案,我只是嘗試一些教程... 這一個正在工作...

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 
<!DOCTYPE html> 
<html> 
    <head> 
     <script type="text/javascript" src="js/jquery-1.10.2.min.js" ></script> 
     <script src="js/Chart.js"></script> 
     <title>JSP Page</title> 
    </head> 
    <body> 
     <h1>Hello World!</h1> 
     <br /> 

     <br/> 


     <br/> 
     <canvas id="canvas" height="450" width="700"></canvas> 

    </body> 
</html> 
<script> 

      $(document).ready(function(){ 
       GetCountryList(); 
      }); 


    function GetCountryList(){ 
     var data2 = ""; 
     $.ajax({ 
      type: "POST", 
      url: "qs", 
      data: "{\"type\":" + "\"country\""+  
      "}", 
      contentType: "application/x-www-form-urlencoded", 
      dataType: "json", 
      success: function(response) { 

       var resultsArray = (typeof response) == 'string' ? eval('(' + response + ')') : response; 



       var data2 = new Array(); 
       for(var i=0; i<resultsArray.length;i++){ 
        data2[i] = resultsArray[i].workgroup; 


        var barChartData = { 
          labels : data2, 
          datasets : [ 
            { 
              fillColor : "rgba(220,220,220,0.5)", 
              strokeColor : "rgba(220,220,220,1)", 
              data : [65,59,90,81,56,55,40,80] 
            } 
          ] 

        }; 
       } 


     var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData); 

      } 


     });     

    } 

</script>