Wednesday, May 29, 2013

Clarifying about including json data in javascript file

Just received a beginner question about passing json data to the amchart.
A friend was confused about inline json object creation and loading external json file

All the following two versions work

Version 1:

    <!-- main.html -->
    <script src="js/amcharts.js" type="text/javascript"></script>
    <script src="js/your_formatted_data.js" type="text/javascript"></script>
    var chart = new AmCharts.AmSerialChart();
    chart.dataProvider = chartData;
    chart.categoryField = "country";
    <!-- js/your_formatted_data.js -->
    var chartData = [
                      {country: "USA", visits: 1234},
                      {country: "HK", visits: 5678},
                    ];


Version 2:

    <!-- main.html -->
    <script src="js/amcharts.js" type="text/javascript"></script>
    var chartData = [
                      {country: "USA", visits: 1234},
                      {country: "HK", visits: 5678},
                    ];
    var chart = new AmCharts.AmSerialChart();
    chart.dataProvider = chartData;
    chart.categoryField = "country";

I would suggest the version one because it is easier to maintain and more readable.
You can change the json data inside your_formatted_data.js without changing the main.html

No comments:

Post a Comment