CanvasJS изменяет тип диаграммы на основе раскрывающегося значения - PullRequest
0 голосов
/ 26 февраля 2019

Я хочу изменить тип диаграммы на основе раскрывающегося значения.Я попробовал и последовал примеру, но он все еще не работал.Я не уверен, какую часть я пропустил.Я использую JavaScript диаграммы и графики из данных JSON с использованием AJAX.Код ниже:

<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>

<script>
window.onload = function () {

var dataPoints = [];

$.getJSON( "<?php echo $url; ?>", function( json ) {

  for (var i = 0; i < json.dates.length; i++) {
        dataPoints.push({
            x: new Date(json.dates[i]),
            y: json.values[i]
        });
    }

    var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    exportEnabled: true,
    theme: "dark2",
    title: {
        text: "REPORT"
    },
    axisY: {
        title: "Qty"
    },
    data: [{
        type: "column", 
        //indexLabel: "{y}", //Shows y value on all Data Points
        yValueFormatString: "#,### Units",
        indexLabelFontColor: "#5A5757",
        indexLabelPlacement: "outside",
        dataPoints: dataPoints
    }]
});

chart.render();
 })
    .done(function(){
        alert("Completed");
    })
    .fail(function(e){
        console.log('error:');
        console.error(e);
    })
    .always(function(){
        alert("always runs");
    });
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change",  function(){
        for(var i = 0; i < chart.options.data.length; i++){
            chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
    }
    chart.render();
});
</script>


Раскрывающийся список:

<select id="chartType" class="form-control" name="chartType">
                                            <option value="column">Column</option>
                                            <option value="line">Line</option>
                                            <option value="bar">Bar</option>
                                            <option value="pie">Pie</option>
                                            <option value="doughnut">Doughnut</option>
                                        </select>

Заранее спасибо.

1 Ответ

0 голосов
/ 28 февраля 2019

Похоже, что проблема с переменной областью , вы создаете диаграмму внутри AJAX, но пытаетесь получить к ней доступ во время изменения типа диаграммы, что приведет к ошибке в консоли браузера.Я бы посоветовал вам сделать это вне AJAX и обновить только dataPoints внутри AJAX.

Вот обновленный / рабочий код (образец JSON, содержащий только 1 dataPoint, хранится в: https://api.myjson.com/bins/18hgaa):

var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
  for (var i = 0; i < json.dates.length; i++) {
    dataPoints.push({
      x: new Date(json.dates[i]),
      y: json.values[i]
    });
  }
}).done(function(){
		chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    exportEnabled: true,
    theme: "dark2",
    title: {
      text: "REPORT"
    },
    axisY: {
      title: "Qty"
    },
    data: [{
      type: "column", 
      //indexLabel: "{y}", //Shows y value on all Data Points
      yValueFormatString: "#,### Units",
      indexLabelFontColor: "#5A5757",
      indexLabelPlacement: "outside",
      dataPoints: dataPoints
    }]
  });
	chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change",  function(){
  for(var i = 0; i < chart.options.data.length; i++){
    chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
  }
  chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
  <option value="column">Column</option>
  <option value="line">Line</option>
  <option value="bar">Bar</option>
  <option value="pie">Pie</option>
  <option value="doughnut">Doughnut</option>
</select>
...