Drawing line chart in chart.js with json response

前端 未结 2 1419
说谎
说谎 2021-02-01 11:38


        
相关标签:
2条回答
  • 2021-02-01 12:02

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

        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.

    0 讨论(0)
  • 2021-02-01 12:06

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

    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.

    0 讨论(0)
提交回复
热议问题