我需要使用Google Chart在zk中创建一个图表,如下所示:

javascript - 如何从zul ZK中的 Controller 获取json对象?-LMLPHP

这是我的控制器:

public class ChartForm extends GenericComposer{

public List<Task> listTask;
public String json;

/* (non-Javadoc)
 * @see org.zkoss.zk.ui.util.GenericComposer#doAfterCompose(org.zkoss.zk.ui.Component)
 */
@Override
public void doAfterCompose(Component comp) throws Exception {
    // TODO Auto-generated method stub
    super.doAfterCompose(comp);

    TaskService ts = new TaskService();

    listTask = ts.getTask();

    json = new Gson().toJson(listTask); // I't OK until here

    System.out.println(json);
}

}


值是:


  [{“ taskName”:“自动化”,“小时”:11},{“ taskName”:“手动”,“小时”:2},{“ taskName”:“报告”,“小时”:2},{ “ taskName”:“工资单”,“小时”:2},{“ taskName”:“ MISC”,“小时”:7}]


我的祖尔:

<zk>
 <window id="HomePage" apply = "com.dom.form.ChartForm" border="none" width="100%" height="100%" style="background-color:green">
<script type="text/javascript" src="https://www.gstatic.com/chart/loader.js"></script>
    <div id="piechart_3d" style="width: 500px; height: 300px;">
    <script type="text/javascript">
      google.charts.load("current", {packages:["corechart"]});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Automation',     11],
          ['Manual',      2],
          ['Report',  2],
          ['Payroll', 2],
          ['MISC',    7]
        ]);

        var options = {
          title: 'My Daily Work Activities',
          is3D: true,
        };


        var chart = new google.visualization.PieChart(zk.Widget.$("$piechart_3d").$n());
        chart.draw(data, options);
      }
    </script>
    </div>

  </window>

</zk>


现在我需要获取json对象并将其插入数据(变量)

var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Automation',     11],
      ['Manual',      2],
      ['Report',  2],
      ['Payroll', 2],
      ['MISC',    7]
    ]);

最佳答案

您可以使用Clients.evalJavaScript();将Json从控制器传递到视图,
像这样 :

function drawChart(jsonObj){
  var data = JSON.parse(jsonObj);
  var chart = new google.visualization.PieChart(zk.Widget.$("$piechart_3d").$n());
  chart.draw(data, options);
}


并在您的控制器中:

TaskService ts = new TaskService();
listTask = ts.getTask();
json = new Gson().toJson(listTask);
Clients.evalJavaScript("drawChart('" + json + "')");

08-15 19:05