将动态json数组传递给Highcharts饼图

reh*_*han 2 arrays json highcharts

我将json编码的字符串(例如,$ TEXT2组成["chrome","15","firefox","20"])从xcode传递到javascript中的数组(例如arr).现在我想传递包含此数组的数组json字符串动态到Highcharts Pie.HTML代码是

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=20, user-scalable=no;" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pie chart</title>

<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">

var chart;
var arr = $TEXT2;

$(document).ready(function(){
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Interactive Pie'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
});
});
</script>
<body>
<br>
<!-- 3. Add the container -->
<div id="container" style="width: 300px; height: 350px; margin: 0 auto"></div>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我试图使用getjson方法,虽然我不知道它的用法.因为我想将我的数组,即arr传递给Highcharts中的data [],我正在做:

$.getJSON("arr", function(json) {
chart.series = json;               
var chart = new Highcharts.Chart(chart);
     });
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决问题.提前致谢.

Mar*_*ark 9

我将在document.ready函数中包装JSON调用,然后将绘图调用包装在getJSON的成功回调中:

$(document).ready(function() {

  $.getJSON("arr", function(json) {

    chart = new Highcharts.Chart({
      chart: {
        renderTo: 'container',
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false
      },
      title: {
        text: 'Interactive Pie'
      },
      tooltip: {
        formatter: function() {
          return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
        }
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: false
          },
          showInLegend: true
      },
      series: [{
        type: 'pie',
        name: 'Browser share',
        data: json
      }]
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

当然,为了实现这一点,您应该修改后端代码以返回HighCharts期望的格式正确的数组数组:

[["chrome",15],["firefox",20]]
Run Code Online (Sandbox Code Playgroud)

您可以在JS中"修复"返回的​​数组,但最好在JSON后端调用中执行此操作.