Highcharts loading data and not plotting

2019-06-02 06:43发布

问题:

I'm trying to load data dynamically into Highcharts but I'm having problems. I tried to do this in a lot of ways and the data seems to be loaded to the JS but the graph is not plotted.

Currently this is my code in jQuery's document ready function:

options = {
    chart: {
        renderTo: 'container',
        zoomType: 'x',
        animation: true,
    },
    title: {
        text: null
    },
    subtitle: {
        text: null
    },
    xAxis: {
        type: 'datetime',
        title: {
            text: null
        },
    },
    yAxis: {
        title: {
            text: 'Size',
        },
    },
    legend: {
        enabled: false
    },

   series: [{
        data: []
    }]
}

$.ajax({
        type: "GET",
        url: "works/load_data.php",
        data: "id=3&mdate=2012-02&mxdate=2012-03",
        success: function (items) {

            var obj = eval(items).load;
            var series = { data: [] };

            $.each(obj, function (itemNo, item) {
                series.data.push(item);
            });

            options.series.push(series);

        },
        cache: false,
});
var chart = new Highcharts.Chart(options);

Nothing happens on the graph. But if I log to console the chart options I get this:

My PHP is echoing the data like this: data = {load:[ {x: Date.UTC(2012,2,1,7,15), y: 0.012},{x: Date.UTC(2012,2,1,7,30), y: 0.068} ... ]}

Seem to be OK, to me at least. But it's not working :( Can someone tell me what I'm doing wrong?? Thanks.

回答1:

AJAX is asynchronous, meaning the call happens after you render the chart. Trying sticking the chart creation after your success event, like so:

$.ajax({
        type: "GET",
        url: "works/load_data.php",
        data: "id=3&mdate=2012-02&mxdate=2012-03",
        success: function (items) {

            var obj = eval(items).load;
            var series = { data: [] };

            $.each(obj, function (itemNo, item) {
                series.data.push(item);
            });

            options.series.push(series);


            var chart = new Highcharts.Chart(options);

        },
        cache: false,
});