0

我正在为我的项目使用谷歌图表 api。我的项目很简单,从 url 获取 json 并显示图表。

我用这样的东西。它工作正常

  var jsonData = $.ajax({
      url: "/files/data.json",
      dataType:"json",
      async: false
      }).responseText;
  var data = new google.visualization.DataTable(jsonData);
  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240});

“/files/data.json”处的 json 数据如下所示

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        .....
      ]
}

实际上我在同一页上有三个图表。我不想发送三个单独的请求来从服务器检索数据。如何在 json 响应中嵌套三个图表的数据。var data会改变jsondata.nest1吗?

我很感激任何帮助。

4

1 回答 1

0

我会做这样的事情:

{
 nest1: [
 {
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        .....
      ]
 },

 {
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        .....
      ]
 },

 {
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        .....
      ]
 }

 ]
}

然后您可以使用 jsonData.nest1[0]、jsonData.nest1[1] 和 jsonData.nest1[2] 访问数据。

一个提示:要使用 ajax JSON 的快捷方式,您可以使用 getJSON http://api.jquery.com/jQuery.getJSON/

希望这可以帮助,

迈克尔

于 2012-08-20T10:45:52.310 回答