简体   繁体   English

使用JSON生成Google图表

[英]generate Google Chart using JSON

I am working on a web application which retrieves JSON data from servlet and uses it to generate chart. 我正在使用一个Web应用程序,该应用程序从servlet检索JSON数据并使用它生成图表。 I am successful in retrieving the requisite json file in Google Chart compliant JSON format but am unable to generate the chart. 我成功检索了符合Google Chart的JSON格式的必需json文件,但无法生成图表。

The jsbin of google chart is in the foll link: http://jsbin.com/hofaqidape/1/watch?html,js,output Google图表的jsbin在以下链接中: http ://jsbin.com/hofaqidape/1/watch?html,js,output

The data var should be generated using JSON and I am doing the following stuff in my servlet 数据变量应使用JSON生成,而我正在servlet中执行以下操作

response.setContentType("application/json");
            String json;
            newClass s =new newClass();
            List<newClass> classes = new ArrayList<newClass>();
            s.setCount(1);
            s.setName("Name");
            classes.add(s);
            s =new newClass();
            s.setCount(2);
            s.setName("Name1");
            classes.add(s);
            s =new newClass();
            s.setCount(3);
            s.setName("Name2");
            classes.add(s);
            s =new newClass();
            s.setCount(1);
            s.setName("Name4");
            classes.add(s);
            json="{ cols :[ {  label :  name  ,  type :  string },{ label :  count  ,  type :  number }], rows :[";
            String ss;int y;
            for(newClass class1:classes)
            {
                ss=class1.getName();
                y=class1.getCount();
                json+="{ c : [{ v : "+ss+" },{ v : "+y+"}]},";
            }
            json=json.substring(0, json.length()-1);
            json+="]}";
            JSONObject js=null;
            try {
                js = new JSONObject(json);
            } catch (ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                out.print(js);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

on the html side I have the foll code for my chart generation: 在html端,我有用于生成图表的foll代码:

$(document).ready(function(){
            $.ajax({
                    url : "Serv",
                    dataType: 'json',
                     contentType: 'application/json',
                    success : function(result) {
                          var dat=result;
                          alert(JSON.stringify(dat));
                          google.load('visualization', '1', {
                                packages: ['corechart', 'bar']
                            });
                            google.setOnLoadCallback(drawBasic);

                            function drawBasic() {

                                var data = new google.visualization.DataTable(dat);

                                var options = {
                                    title: 'Motivation Level Throughout the Day',
                                    hAxis: {
                                        title: 'Name'
                                    },
                                    vAxis: {
                                        title: 'Count'
                                    }
                                };

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

                                chart.draw(data, options);
                            }

                    },
            complete: function()
            {
                alert('done');
            }
                });
        });

alert(JSON.stringify(dat)) gives the alert as alert(JSON.stringify(dat))给出警报为

{"cols":[{"label":"name","type":"string"},{"label":"count","type":"number"}],"rows":[{"c":[{"v":"Name"},{"v":1}]},{"c":[{"v":"Name1"},{"v":2}]},{"c":[{"v":"Name2"},{"v":3}]},{"c":[{"v":"Name4"},{"v":1}]}]} {“ cols”:[{“ label”:“名称”,“ type”:“字符串”},{“ label”:“ count”,“ type”:“ number”}],“ rows”:[{“ c“:[{” v“:”名称“},{” v“:1}]},{” c“:[{” v“:” Name1“},{” v“:2}]}, {“ c”:[{“ v”:“ Name2”},{“ v”:3}]},{“ c”:[{“ v”:“ Name4”},{“ v”:1}] }]}

which is a valid JSON. 这是有效的JSON。

how do I generate the chart using this data just like I did in jsbin? 像在jsbin中一样,如何使用这些数据生成图表?

google.setOnLoadCallback() set up a callback function to execute when Google Visualization API loaded, so google.load needs to load from the front explicitly. google.setOnLoadCallback()设置了一个回调函数,以便在加载Google Visualization API时执行,因此google.load需要从前端显式加载。 I am recalling it when i worked on them lately. 我最近在研究它们时回想起它。 My recommendation would be to move google.load and drawBasic() outside from AJAX call and use them in success of call, like this... 我的建议是将google.loaddrawBasic()AJAX调用中移出,并在调用success时使用它们,像这样...

$(document).ready(function(){
    google.load('visualization', '1', {
        packages: ['corechart']
    });

    function drawBasic(d) {
      var data = new google.visualization.DataTable(d);
      var options = {
         title: 'Motivation Level Throughout the Day',
         hAxis: {
            title: 'Name'
         },
         vAxis: {
            title: 'Count'
         }
      };

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    $.ajax({
        url : "Serv",
        dataType: 'json',
         contentType: 'application/json',
        success : function(result) {
          google.setOnLoadCallback(drawBasic(JSON.stringify(result)));
        },
        complete: function(){
           // whatever..
        }
    });

 });

Update: You only need to specify packages: ['corechart'] which will define most basic charts, including the pie , bar , and column charts. 更新:您只需要指定packages: ['corechart'] ,它将定义大多数基本图表,包括piebarcolumn

finally got the answer to this question. 终于得到了这个问题的答案。 removed google.setOnLoadCallback() and called drawBasic() function from ajax call itself. 从ajax调用本身中删除了google.setOnLoadCallback()并调用了drawBasic()函数。 somehow setOnLoadCallback() and $(document).ready() doesnt seem to coexist. setOnLoadCallback()和$(document).ready()以某种方式似乎并不共存。

working code: 工作代码:

<script>
google.load('visualization', '1', {
        packages: ['corechart']
    });

    function drawBasic(d) {
     var data = new google.visualization.DataTable(d);
      var options = {
         title: 'Sample Data',
         hAxis: {
            title: 'Name'
         },
         vAxis: {
            title: 'Count'
         },
         width: 600,
         height: 240
      };

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }  

                $(function(){
        $("#dd").change(function(){
            if($(this).val()!='null')
          {
                $.ajax({
            url : "Serv",
            data: {dd1:$(this).val()},
            dataType: 'json',
             contentType: 'application/json',
            success : function(result) {
              drawBasic(result);
            },
            complete: function(){
               // whatever..
            }
        })  ;
          }
            else
                {
                $("#chart_div").empty();
                alert('please select');
                }
        });
        });
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM