как получить данные старшей диаграммы из внешнего JSON - PullRequest
0 голосов
/ 15 мая 2018

У меня есть круговая диаграмма из плагина highchart, мне нужно получить данные из внешнего json, но здесь, в соответствии со структурой json, у меня возникают трудности с получением диаграммы, в 'chart1' должны присутствовать данные div chart1 и в 'chart2'Данные div chart2 должны поступить из json. Я дал html, javascript и json также в следующем коде. Заранее спасибо

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://code.highcharts.com/highcharts.js"></script>

<script src="https://code.highcharts.com/modules/exporting.js"></script>

</head>
<body>
<div id="chart1" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<div id="chart2" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

JAVASCRIPT

$.getJSON('http://localhost/highcharts/json-data/chart.json', function (data) {

    // Make codes uppercase to match the map data
    $.each(data, function () {
       // this.code = this.code.toUpperCase();
    });
Highcharts.chart('container', {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'Browser market shares in January, 2018'
    },
    tooltip: {
       // pointFormat: ' <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
               format: '<b>{point.name}</b>',
            }
        }
    },
    series: [{
        name: 'Brands',
       // colorByPoint: true,
        data: data,
    }]
});
});

JSON (chart.json)

{
    "chart1": [{
            "name": "name1",
            "y": 6
        },
        {
            "name": "name2",
            "y": 12
        },
        {
            "name": "name3",
            "y ": 18
        },
        {
            "name ": "name3",
            "y ": 10
        }
    ],
    "chart2": [{
            "name ": "name1",
            "y ": 1981
        },
        {
            "name ": "name2",
            "y ": 6
        }
    ]
}

1 Ответ

0 голосов
/ 16 мая 2018

Вам нужно что-то сделать с входящими данными JSON.Я симулировал получение данных, возвращаемых из ajax, помещая их в переменную.Важная часть такова:

$.each(jsondata, function(chartDiv) {
  //create each chart here
  //chartDiv is the top level of the json structure
  //jsondata[chartDiv] gives you the data for each chart.
  ...
}

var jsondata = {
  "chart1": [{
      "name": "name1",
      "y": 6
    },
    {
      "name": "name2",
      "y": 12
    },
    {
      "name": "name3",
      "y": 18
    },
    {
      "name ": "name3",
      "y": 10
    }
  ],
  "chart2": [{
      "name ": "name1",
      "y": 1981
    },
    {
      "name ": "name2",
      "y": 6
    }
  ]
}

// Make codes uppercase to match the map data
$.each(jsondata, function(chartDiv) {
  Highcharts.chart({
    chart: {
      renderTo: chartDiv,
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type: 'pie'
    },
    title: {
      text: 'Browser market shares in January, 2018'
    },
    tooltip: {
      // pointFormat: ' <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
          enabled: true,
          format: '<b>{point.name}</b>',
        }
      }
    },
    series: [{
      name: 'Brands',
      // colorByPoint: true,
      data: jsondata[chartDiv],
    }]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://code.highcharts.com/highcharts.js"></script>

<script src="https://code.highcharts.com/modules/exporting.js"></script>

  <div id="chart1" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
  <div id="chart2" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

Также обратите внимание, что ваш входящий json содержит ошибок , у вас есть "y ": 18, в имени параметра не должно быть пробела,Желательно, чтобы он не был заключен в кавычки.(Я исправил это для примера.)

Рабочая скрипка: https://jsfiddle.net/ewolden/pq6L219g/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...