javascript Highcharts:如何将数据从 JSON 加载到 xAxis.categories 和 series.data?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6563997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:06:57  来源:igfitidea点击:

Highcharts: How to load data from JSON to xAxis.categories and series.data?

javascriptjsonhighcharts

提问by user826224

Sorry for the beginner question.

很抱歉初学者的问题。

This is how my JSON looks like:

这是我的 JSON 的样子:

[
   ["junior college", "Primary", "secondary", "polytechnic"],
   ["4", "3", "1", "1"]
]

And this is my HTML,

这是我的 HTML,

var chart; // global
var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'bar'
    },
    title:{
        text: 'No. Schools for different levels'
    },
    xAxis:{
        title:'Education Level',
        categories:[]
    },
    yAxis:{
        title:{
            text:'No. Of Schools'
        }
    },
    series:[{
        name: "No. Schools",
        data: []
    }]
};

$.getJSON('loadData.php', function(JSONresult) {
    yData = options.series[0].data; //Array to store data for y column
    xData = options.xAxis.categories; //Array to store data for x column

    xDataObj = JSONresult[0];
    yDataObj = JSONresult[1];

    for(var key in xDataObj){
        xData.push(xDataObj[key]);
    }

    for(var key in yDataObj){
        yData.push(parseFloat(yDataObj[key]));
    }

I tried to execute the code, firebug shows no error but the chart never shows up. Could you help point out where did I go wrong?

我尝试执行代码,firebug 没有显示错误,但图表从未出现。你能帮忙指出我哪里出错了吗?

采纳答案by user826224

I found out the solution.

我找到了解决方案。

In my php script, I have to cast integer to the series data,

在我的 php 脚本中,我必须将整数转换为系列数据,

(int)$variable;

so the JSON out put would be

所以JSON输出将是

[4, 3, 1, 1]

and the chart will be rendered.

并且图表将被呈现。

Thank you ppl :)

谢谢大家:)

回答by Larsenal

You need to do something like this to instantiate and render the chart:

你需要做这样的事情来实例化和呈现图表:

chart = new Highcharts.Chart(options);

This could go at the end of your getJSON response function.

这可能会在您的 getJSON 响应函数结束时进行。