使用ajax数据绘制Chart.js并响应。一些问题和疑问 [英] Draw a Chart.js with ajax data and responsive. A few problems and questions

查看:147
本文介绍了使用ajax数据绘制Chart.js并响应。一些问题和疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chart.js( http://www.chartjs.org/docs/)用于制图。

I am using Chart.js (http://www.chartjs.org/docs/) for charting.

我需要从Ajax请求中获取数据并使图表具有响应性。

I need to get the data from an Ajax request and the chart to be responsive.

在我的HTML代码中,我添加了如下画布:

In my HTML code I added a canvas as follows:

<div>
  <canvas id="userscreated" class="plot" data-url="/stats/userscreated"></canvas>
</div>

在我的javascript(JQuery)代码中,我有:

And in my javascript (JQuery) code I have:

var data2;

$.ajax({
  url: $('#userscreated').data('url'),
  async: true,
  dataType: 'json',
  type: "get",
}).done(function (data) {

    data2 = data;

    // Draw chart
    var context = $('#userscreated').get(0).getContext("2d");
    var wrapper = $('#userscreated').parent();
    var width = $('#userscreated').attr('width', $(wrapper).width());

    new Chart(context).Line(
    {
      labels: data.Dates,
      datasets: [
        { fillColor: #404040, data: data.Users }
      ]
    },
    { animation: false }
  );

});

// Redraw the chart with the same data
$(window).resize(function () {

  var context = $('#userscreated').get(0).getContext("2d");
  var wrapper = $('#userscreated').parent();
  var width = $('#userscreated').attr('width', $(wrapper).width());

  new Chart(context).Line(
    {
      labels: data2.Dates,
      datasets: [
        { fillColor: #404040, data: data2.Users }
      ]
    },
    { animation: false }
  );

});

问题


  1. 在调整窗口大小时,图表没有调整大小。

  2. 有没有更好的代码来执行此操作?我想我会重复很多代码。

  3. 在Google中,绘图很快。在firefox中有时会挂起一段时间。
    我的代码有什么问题吗?

  4. 请求是否异步?

  1. The chart is not being resized on window resize.
  2. Is there better code to do this? I think I am repeating to much code.
  3. In Google the drawing is fast. In firefox sometimes it hangs for a while. Is anything wrong with my code?
  4. Should the request be async or not?


推荐答案

您可以使异步AJAX调用没问题。只有在成功回调触发后才设置图表,这一点非常重要。否则,您将无法定义画布上下文的问题。第一次调用respondCanvas进行初始设置,而后续调用进行调整大小。

You can make async AJAX calls no problem. It's just important that you setup the chart only after the success callback fires. Otherwise, you'll get issues with your canvas context not being defined. The first call to respondCanvas does the initial setup while the subsequent calls do the resizing.

这对我有用:

var max = 0;
var steps = 10;
var chartData = {};

function respondCanvas() {
    var c = $('#summary');
    var ctx = c.get(0).getContext("2d");
    var container = c.parent();

    var $container = $(container);

    c.attr('width', $container.width()); //max width

    c.attr('height', $container.height()); //max height                   

    //Call a function to redraw other content (texts, images etc)
    var chart = new Chart(ctx).Line(chartData, {
        scaleOverride: true,
        scaleSteps: steps,
        scaleStepWidth: Math.ceil(max / steps),
        scaleStartValue: 0
    });
}

var GetChartData = function () {
    $.ajax({
        url: serviceUri,
        method: 'GET',
        dataType: 'json',
        success: function (d) {
           chartData = {
                labels: d.AxisLabels,
                datasets: [
                    {
                        fillColor: "rgba(220,220,220,0.5)",
                        strokeColor: "rgba(220,220,220,1)",
                        pointColor: "rgba(220,220,220,1)",
                        pointStrokeColor: "#fff",
                        data: d.DataSets[0]
                    }
                ]
            };

            max = Math.max.apply(Math, d.DataSets[0]);
            steps = 10;

            respondCanvas();
        }
    });
};

$(document).ready(function() {
    $(window).resize(respondCanvas);

    GetChartData();
});

如果要在两次通话之间插入一小段延迟,可以使用超时:

If you want to insert a small delay between calls, you can use a timeout:

$(document).ready(function() {
    $(window).resize(setTimeout(respondCanvas, 500));

    GetChartData();
});

如果您的图表上有大量数据集,延迟将使您的调整大小更具响应性。

The delay will make your resizing more responsive in case you have a large dataset on your graph.

这篇关于使用ajax数据绘制Chart.js并响应。一些问题和疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆