Is there a way to enter Highchart series data with

2019-08-28 01:37发布

问题:

I have been working on getting data into a highchart graph with much difficulty.

Eventually I had to go with using eval(data).

Is there a better way to do this?

JSFiddle Example

$(function () {
    var test = "[[Date.UTC(2013, 4, 08), 45.95],[Date.UTC(2013, 5, 28), 19.95]]"; 
    $('#container').highcharts({
        chart: {
        },
        xAxis: {
            type: 'datetime'
        },

        series: [{
            data: eval(test)
        }]
    });
});

UPDATE 1

My actual objective is to pass a JSON object into a function (as shown below) then get the required strings and pass them to the series input.

The following is still not working.

function showPriceChart(priceData) {

    var json = jQuery.parseJSON(priceData);
    var pricePrices = [ json.pricePrices ];

            // This works if I use eval below
            // var pricePrices = '['+json.pricePrices+']';


    /// Other chart config goes here

    series: [{
            name: 'Retailer Price',
            data: pricePrices
        }, {
            name: 'RRP',
            data: rrpPrices
        }]
    });
    }

Here is the JSON object from php using print_r():

{"pricePrices":"[Date.UTC(2013, 4, 8), 67],[Date.UTC(2013, 5, 28), 29]","salePrices":"[Date.UTC(2013, 4, 8), ],[Date.UTC(2013, 5, 28), ]","rrpPrices":"[Date.UTC(2013, 4, 8), 67],[Date.UTC(2013, 5, 28), 67]"}

回答1:

you were really close from your goal. The following is working :

(http://jsfiddle.net/G6jrU/3/)

$(function () {

    var test =[ [ Date.UTC(2013, 4, 08),  45.95 ], 
                [ Date.UTC(2013, 5, 28), 19.95  ]  ];


    $('#container').highcharts({
        chart: {
        },
        xAxis: {
            type: 'datetime'
        },

        series: [{ data : test }]

    });
});

Rq : You might use JSON to serialize/unserialize data if you need to.



回答2:

The problem is that you are using Date.UTC() function, so you need to use eval. How about passing numbers(timestamps in milliseconds) instead of that functions? So, your JSON should look this way:

{
 "pricePrices":[1367971200000, 67],[1372377600000, 29],
 "salePrices":[1367971200000, ],[1372377600000, ], //where are values ?!
 "rrpPrices":[1367971200000, 67],[1372377600000, 67] //without extra '"'!! 
}

Also, there is some missing values for second series, where are they?