包含 JSON 数据的 C3 图表

C3 chart with JSON data

我正在尝试使用来自 SQL 数据库的动态数据填充 C3 图表。我有 c# web 方法,当我的 javascript 调用时会生成以下 JSON 字符串

[{"y":"5","item1":"Lion Wharf"},{"y":"31","item1":"Millbrook Park P2"},{"y":"84","item1":"Pinfield Meadows"}]

我在页面加载时使用以下 javascript 但出现错误 "a.forEach is not a function"

      $.ajax({
            type: "POST",
            url: "additions.aspx/GetPiechartData",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (result) {
                OnSuccess(result.d);
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });

        function OnSuccess(response) {
            var abc = JSON.stringify(response);
            window.location.replace(response);
            var chart = c3.generate({
                bindto: '#chart-var-project',
                data: {
                    json: response,
                    keys: {
                        x: 'y',
                        value: ['item1']
                    },
                    type: 'donut'
                },
                donut: {
                    title: "Approval",
                    width: 40,
                    label: {
                        show: false
                    }
                },
                color: {
                    pattern: ["#ff9800", "#78c350", "#f7531f"]
                }
        });

我是 Javascript 的新手,非常感谢您的指点

谢谢!

您必须格式化您的 json 响应,以符合 Donut 图表类型的 C3 预期格式。

function OnSuccess(response) {
    var data = {};
    var value = [];
    JSON.parse(response).forEach(function(d) {
        data[d.item1] = d.y;
        value.push(d.item1);
    });

    c3.generate({
                data: {
                    json: [data],
                    keys: {
                        value : value
                    },
                    type: 'donut'
                },
                donut: {
                    title: "Approval",
                    width: 40,
                    label: {
                        show: false
                    }
                },
                color: {
                    pattern: ["#ff9800", "#78c350", "#f7531f"]
                }
        })
}

您的服务器通常会输出一个字符串,因此使用 JSON.parse 会将此字符串转换为 json 对象。

function OnSuccess(response) {

    var jsonData = response.d;

    var chart = c3.generate({
        bindto: '#chart-var-project',
        data: {
            json: JSON.parse(jsonData),
        }
    });

}