【问题标题】:How to use ajax call to populate line graph in highcharts如何使用ajax调用在highcharts中填充折线图
【发布时间】:2014-03-29 02:52:52
【问题描述】:

我正在尝试在 asp.net 中使用 highcharts 绘制一个简单的折线图。我无法画出任何东西。到目前为止,这是我所得到的:

var chart;

    $(document).ready(function () {
        chart = new Highcharts.Chart({  
            chart: {
                renderTo: 'container',
                type: 'line'  
            },
            title: {
                text: 'Rank vs. Time'
            },    
            xAxis: {
                numerical: [],
                title: {
                    text: 'Year'
                }
            },
            yAxis: {
                title: {
                    text: 'Rank'
                }
            },

        });
        getData();
    });

function getData() {
        $.ajax({
            type: "GET",
            url: "/api/Name/GetBoyNamesByYear?name=matthew",
            success: function (data) {
                chart.addSeries({
                    name: "Matthew",
                    data: data
                });
            },
            cache: false
        });
    }    

我的 ajax 以

的格式返回一些东西
 [{"$id":"1","Year":1995,"Rank":2},{"$id":"2","Year":1996,"Rank":2},{"$id":"3","Year":1981,"Rank":3},{"$id":"4","Year":1982,"Rank":3}, .......

如果它在我的 html 中很重要,我有:

<div id="container" style="width:100%; height:400px;"></div>

编辑:解决了这个问题。
data.sort(函数(a,b){ 返回 a.Year > b.Year ? 1:-1; });

                data = $.map(data, function (i) {
                    return { x: i['Year'], y: i['Rank'] };
                });

                chart.addSeries({
                    name: "Matthew",
                    data: data,
                    marker: {
                        enabled: true,
                        radius: 1
                    },
                });

【问题讨论】:

    标签: jquery asp.net-mvc charts highcharts


    【解决方案1】:

    你有两个问题。

    1.) Highcharts 不知道用您的任意系列属性绘制什么。什么对应于 X 和 Y 值? how the data needs to be formatted 非常具体。我假设您希望 Year 作为 X 和 Rank 作为 Y。

    2.) 您的数据未按 X 值排序。

    结合这两个问题:

    var data = [{"$id":"1","Year":1995,"Rank":2},{"$id":"2","Year":1996,"Rank":2},{"$id":"3","Year":1981,"Rank":3},{"$id":"4","Year":1982,"Rank":3}];
    
    data.sort(function(a,b){return a['Year'] > b['Year']});
    
    data = $.map(data, function(i){
        return {x: i['Year'],y: i['Rank']};
    });
    

    这是fiddle

    【讨论】:

    • 好吧,这是有道理的。我会试试。我的问题是,这会比我上面所做的编辑慢吗?现在它需要很长时间来生成图表,比如通过上面我添加所有单个点的方式来完成大约 8 秒。
    • 发现错误出在数据排序上。编辑上面的代码以显示工作版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多