Creating Google Pie Chart based on JSON data using

2019-07-07 06:27发布

问题:

I tried to create a pie chart based on example here

In my controller (mycontroller/json) i have the following code:

public function json(){

$whatever = '{
"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}]},
    {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
    {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
    {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
  ]
}';
echo $whatever;
}

In my view i have the following code (partial code is shown)

var jsonData = $.ajax({
    url: "<?= base_url()?>index.php/bunker/json",
    dataType:"json",
    async: false
    }).responseText;

// Create and populate the data table.
var popularCategory = google.visualization.DataTable(jsonData);
new google.visualization.PieChart(document.getElementById('category')).draw(popularCategory,
    {title:"Popularity by Category"});

And lastly i have a div with an id called 'category'. However, i always get a message saying data is not defined.

A quick debug using firebug, i receive no error, the $whatever variable is also treated as a proper JSON format. What mistakes have i made here?

cheers,

回答1:

instead of:

var popularCategory = google.visualization.DataTable(jsonData);

you must have:

var popularCategory = new google.visualization.DataTable(jsonData);


回答2:

Your json variable has data in incorrect format. Please check the pie chart example here:

https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart



回答3:

Try the php json encode function:

echo json_encode($whatever);

And also, make sure you start using console.log(jsonData) because the browser console will output the 'jsonData' variable similar to print_r in php. I never get json formatting correct the first time so the console.log(jsonData) feature is absolutely killer.