开发者

adding series to highcharts from JSON

I'm trying to add a series to a highcharts chart from JSON data. The json has dates and y values:

{Date.UTC(2011,8,1): 47, Date.UTC(2011,8,2): 78}

and the javascript function I currently have, which adds the series but the dates don't seem to work, is:

function requestData() {
$.ajax({
    url: 'chartData.php',
    success: function(items) {

        var series = {
            id: 'series',
            name: 'JSON Data',
            data: []
            }

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

        chart.addSeries(series)开发者_运维知识库;

    },
    cache: false
});
 }

Can anyone help me finish off this query to get the chart working? Thanks in advance for the help!

EDIT: I SOLVED THIS - SEE ANSWER BELOW FOR HOW I DID IT


I figured this out. Here's how I did it in case anyone else has the same question:

In my script that generates the JSON data, I did the following:

    header('Content-type: text/json');

    //Placeholder - random data for now
    $x1 = "2011-8-1";
    $y1 = rand(0, 100);

    $x2 = "2011-8-2";
    $y2 = rand(0, 100);

    //Generate this array from database data
    $arr = array($x1 => $y1, $x2 => $y2);

    echo json_encode($arr);

Then, in the ajax script that adds the series to the chart, I did the following:

    function requestData() {
 $.ajax({
    url: 'chartData.php',
    success: function(json) {

        var series = {
            id: 'series',
            name: 'JSON Data',
            data: []
            }

        $.each(json, function(date,value) {
            xval = date.split("-");
            x = Date.UTC(xval[0], xval[1] - 1, xval[2]);
            series.data.push([
                x,
                value
            ]);
        });

        chart.addSeries(series);

    },
    cache: false
});
}


In an example from a project I'm working on right now, I evaluate the series data from an array like this. Maybe that is cheating, but I at least got it to work :)

var xAxisCat = new Array();
var hSeries = new Array();
for (var datevote in contestantObject.contestants[cObj].votes)
{
    xAxisCat.push(datevote);
    hSeries.push(contestantObject.contestants[cObj].votes[datevote]);
}
var setSeries = "["+hSeries+"]";

And then, at the series creation I evaluate the created array instead:

series: [{
         name: contestantObject.contestants[cObj].name,
         data: eval(setSeries)
         }]


Check the response(JSON DATA) coming through ajax having datatype as object or not. Because highcharts will work it the response is of datatype as object.

If it is returning as string then, convert it into object using eval('(' + response + ')')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜