Loading external json file in highchart

2019-09-12 14:35发布

When loading external JSON file in HighCharts it shows nothing in the browser. I have following JSON data. I have included highchart.js and jquery.js in the head of my HTML code, but still I cannot get a bar chart in my browser. No error is shown in console when checking the console.

var json = [{
    "key": "Apples",
    "value": "4"
}, {
    "key": "Pears",
    "value": "7"
}, {
    "key": "Bananas",
    "value": "9"
}];

var processed_json = new Array();
$.map(json, function(obj, i) {
    processed_json.push([obj.key, parseInt(obj.value)]);
});

$('#container').highcharts({
    chart: {
        type: 'column'
    },
    xAxis: {
        type: "category"
    },
    series: [{
        data: processed_json
    }]
});

1条回答
成全新的幸福
2楼-- · 2019-09-12 14:56

That is because the order of execution is different than we expect. ie The JSON loading section execution is happening before it get initialized.

You can put the JSON loading section code in one function and call that function after initialization function is completed(.success or .done in the HTML element's event).

I had one AJax function so I called this JSON loading function in the success of that AJAX call.

Code:

var json = [{
    "key": "Apples",
    "value": "4"
}, {
    "key": "Pears",
    "value": "7"
}, {
    "key": "Bananas",
    "value": "9"
}];

var processed_json = new Array();
$.map(json, function(obj, i) {
    processed_json.push([obj.key, parseInt(obj.value)]);
});
if (processed_json.length != 0) {
   loadJson();
}

function loadJson() {
    $('#container').highcharts({
        chart: {
            type: 'column'
        },
        xAxis: {
            type: "category"
        },
        series: [{
            data: processed_json
        }]
    });
}
查看更多
登录 后发表回答