简体   繁体   中英

json to javascript - google charts

In the past I have used the following method to parse the json data appropriately so I can populate a select box:

var request = null;

request = $.ajax({
  type: "POST",
  url: "url goes here",
  dataType: 'text',
  success: function(returned) {
    returned = JSON.parse(returned)

    $.each(returned, function(selectid, item) {
      var sel = $("#" + selectid).get(0);
      sel.options.length = 0;

      $.each(item, function(i, subitem) {
        sel.options[i] = new Option(subitem.text, subitem.value);
      });
    });
    request = null;
  }
});

How do I apply the same technique to the code below, but without a select box, just parse the json into the drawChart function?

$.ajax({
  url: 'chart_json.aspx',
  type: 'POST',
  dataType: 'text',
  success: function(data) {
    drawChart(data);
  }
});

I think your problem lies in your ajax response, i'd do the following:

in your response:

{ 
  graphData : [
    ['user1',{v:0.00, f:'0.00'}],
    ['user2',{v:0.00, f:'0.00'}],
    ['user3',{v:0.00, f:'0.00'}],
    ['user4',{v:0.00, f:'0.00'}],
    ['user5',{v:0.00, f:'0.00'}]
  ],
  status : "ok"
}

in your js:

$.ajax({
  url: 'get_json.aspx',
  type: 'POST',
  dataType: 'json',//this is important
  success: function(data) {
    //this is not vital, but it's nice to check the response
    if(typeof data === "object" && data.status === "ok"){
        graphData = data.graphData;
        drawVisualization(graphData);
    }
  }
});

Hope this helps, Sinan.

$.ajax({
  url: 'get_json.aspx',
  type: 'POST',
  dataType: 'json', // as noted by Sinan
  success: function(data) {
    drawVisualization(data);
  }
});

function drawVisualization(serverData) {
    var chartData = [];
    for(var i = 0; i < serverData.length; i++) {
      chartData.push([serverData[i][0], serverData[i][1].v]);
    }
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'WIP');
    data.addColumn('number', 'Percentage');
    data.addRows(chartData);
    new google.visualization.PieChart(document.getElementById('visualization')).draw(data, {width: 400, height: 240, is3D:true});     
}

The chartData array needs to have 2 columns (since you call addColumn twice on the google.visualization.DataTable) with a string and a number in each row.

Example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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