javascript 使用 json 响应在 chart.js 中绘制折线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24929931/
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-28 03:36:07  来源:igfitidea点击:

Drawing line chart in chart.js with json response

javascriptjqueryajaxjsonchart.js

提问by xrcwrn

<script type="text/javascript">
            $(function() {
                $.ajax({
                    type: "POST",
                    url: "BillnAmount",
                    cache: false,
                    dataType: 'json',
                    success: function(data) {
                        console.log(data);

                        var data = {
                            labels: ["January", "February", "March", "April", "May", "June", "July"],
                            datasets: [
                                {
                                    label: "My First dataset",
                                    fillColor: "rgba(220,220,220,0.2)",
                                    strokeColor: "rgba(220,220,220,1)",
                                    pointColor: "rgba(220,220,220,1)",
                                    pointStrokeColor: "#fff",
                                    pointHighlightFill: "#fff",
                                    pointHighlightStroke: "rgba(220,220,220,1)",
                                    data: [65, 59, 80, 81, 56, 55, 40]
                                },
                                {
                                    label: "My Second dataset",
                                    fillColor: "rgba(151,187,205,0.2)",
                                    strokeColor: "rgba(151,187,205,1)",
                                    pointColor: "rgba(151,187,205,1)",
                                    pointStrokeColor: "#fff",
                                    pointHighlightFill: "#fff",
                                    pointHighlightStroke: "rgba(151,187,205,1)",
                                    data: [28, 48, 40, 19, 86, 27, 90]
                                }
                            ]
                        };
                        var ctx = $("#myChart").get(0).getContext("2d");
                        var myNewChart = new Chart(ctx);
                        var myLineChart = new Chart(ctx).Line(data);
                    }
                });
            });
        </script>

I am calling a url with ajax and getting its response in json format.

我正在使用 ajax 调用 url 并以 json 格式获取其响应。

Inside ajax call I am drawing Line chart with Chart.jswhich is working properly.

在 ajax 调用中,我正在绘制折线图,Chart.js该折线图工作正常。

Now I want to change above chart value with json response data my json response value is

现在我想用 json 响应数据更改上面的图表值我的 json 响应值是

  {"billDetails":
 [{"invoiceDate":"2014-07-24T00:00:00","totalAmount":1031.00,"totalBills":1},  
 {"invoiceDate":"2014-07-15T00:00:00","totalAmount":7281.00,"totalBills":3},
 {"invoiceDate":"2014-07-12T00:00:00","totalAmount":14841.00,"totalBills":7},
 {"invoiceDate":"2014-07-11T00:00:00","totalAmount":1294.00,"totalBills":3},
 {"invoiceDate":"2014-07-10T00:00:00","totalAmount":674.00,"totalBills":3},
 {"invoiceDate":"2014-07-09T00:00:00","totalAmount":2.00,"totalBills":1},
 {"totalAmount":114.00,"totalBills":10}]}

What changes should I do so it must display data from json response

我应该做哪些更改,以便它必须显示来自 json 响应的数据

Edit:I tried this

编辑:我试过这个

var data1;
  $.each(data.billDetails, function(i, value) {
                        data1 = {
                            labels: data.billDetails[i].invoiceDate,
                            datasets: [
                                {
                                    label: "My First dataset",
                                    fillColor: "rgba(220,220,220,0.2)",
                                    strokeColor: "rgba(220,220,220,1)",
                                    pointColor: "rgba(220,220,220,1)",
                                    pointStrokeColor: "#fff",
                                    pointHighlightFill: "#fff",
                                    pointHighlightStroke: "rgba(220,220,220,1)",
                                    data: data.billDetails[i].totalBills
                                },
                                {
                                    label: "My Second dataset",
                                    fillColor: "rgba(151,187,205,0.2)",
                                    strokeColor: "rgba(151,187,205,1)",
                                    pointColor: "rgba(151,187,205,1)",
                                    pointStrokeColor: "#fff",
                                    pointHighlightFill: "#fff",
                                    pointHighlightStroke: "rgba(151,187,205,1)",
                                    data: data.billDetails[i].totalAmount
                                }
                            ]
                        };
                    });

On console it is showing following

在控制台上它显示以下

Uncaught TypeError: Cannot read property 'x' of undefined 

My data in format

我的数据格式

2014-07-24T00:00:00 1 1031 
2014-07-15T00:00:00 3 7281 
2014-07-12T00:00:00 7 14841
2014-07-11T00:00:00 3 1294
2014-07-10T00:00:00 3 674 
2014-07-09T00:00:00 11 116 

It is showing only following image

它仅显示以下图像

enter image description here

在此处输入图片说明

回答by Kevin Sandow

You're on the right track, you'll have to iterate over your json and convert it into an structure chart.js will understand.

您走在正确的轨道上,您必须遍历您的 json 并将其转换为 chart.js 会理解的结构。

You should start with an empty structure containing all the static information:

您应该从一个包含所有静态信息的空结构开始:

var chartData = {
  labels: [], // currently empty will contain all the labels for the data points
  datasets: [
    {
      label: "Total Bills",
      fillColor: "rgba(220,220,220,0.2)",
      strokeColor: "rgba(220,220,220,1)",
      pointColor: "rgba(220,220,220,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: [] // currently empty will contain all the data points for bills
    },
    {
      label: "Total Amount",
      fillColor: "rgba(151,187,205,0.2)",
      strokeColor: "rgba(151,187,205,1)",
      pointColor: "rgba(151,187,205,1)",
      pointStrokeColor: "#fff",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(151,187,205,1)",
      data: [] // currently empty will contain all the data points for bills
    }
  ]
};

So far this will not print your chart, but it contains all the necessary information, like line labels and colors.

到目前为止,这不会打印您的图表,但它包含所有必要的信息,如线条标签和颜色。

Now iterate over your array:

现在迭代你的数组:

$.each(data.billDetails, function(position, billDetail) {
  // first use the invoiceDate as a label
  if (billDetail.invoiceDate) {
    // You should probably format that
    chartData.labels.push(billDetail.invoiceDate); 
  } else {
    // your last data entry doesn't have an invoiceDate
    chartData.labels.push(''); // blank or think of something creative
  }

  // add the totalBills and totalAmount to the dataset
  chartData.datasets[0].data.push(billDetail.totalBills);
  chartData.datasets[1].data.push(billDetail.totalAmount);
});

And now you can let chart.js render the chartData.

现在你可以让 chart.js 渲染chartData.

回答by RandomBoy

Your JSON results should be same structure as chardata, and then you make this

您的 JSON 结果应该与 chardata 具有相同的结构,然后您将其设为

    var charData = 
    {
        labels = [\months]
        datasets: data.datasets
    }

in case that your response (in my case data.datasets) has sam structure like is hardcoded in those examples.

以防您的响应(在我的情况下是 data.datasets)具有像在这些示例中硬编码的 sam 结构。