Javascript数组未初始化

时间:2015-07-14 19:26:58

标签: javascript jquery arrays ajax chart.js

传入另一个对象数组时,我遇到了javascript数组的问题。我尝试过网上出来的一切,但没有任何效果。

dataValues[dataValues.length] = (v.potroseno_tekucine);上的api获取数据时,问题就行了。它使用labelValues。当我在循环中警告数据时它没问题,但是当它需要处理时,它看起来像是未定义的。但是,例如,当我在var数据之前提醒(dataValues.length)时,它的工作正常。

$(document).ready(function () {
var ctx = document.getElementById("PodrumarstvoDetalji").getContext("2d");
var labelValues = [];
var dataValues = [];
$.ajax({
    url: root + "api/StatistikaApi/GetPodrumarstvoChart/?vinograd_id=10",// + $("#vinograd_id").val(),
    type: "Get",
    contentType: 'json',
    dataType: 'json',
    success: function (data) {
        $.each(data, function (k, v) {
            labelValues[labelValues.length] = v.opis;
            dataValues[dataValues.length] = (v.potroseno_tekucine);
        });
    },
    error: function (msg) { alert(msg); }
});
var data = {
    labels: labelValues,
    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: "#ddd",
            pointHighlightFill: "#ddd",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: dataValues
        }/*,
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#ddd",
            pointHighlightFill: "#ddd",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }*/
    ]
};


var myLineChart = new Chart(ctx).Line(data);
});

有人能帮帮我吗?我尝试了推,切片,连续但没有...

1 个答案:

答案 0 :(得分:1)

Ajax调用是异步的...这意味着在从ajax请求获取任何响应之前将设置data

为了解决这个问题,您需要在ajax成功回调函数中创建数据:

$.ajax({
    success: function (data) {
        $.each(data, function (k, v) {
            labelValues.push(v.opis);
            dataValues.push(v.potroseno_tekucine);
        });
        var data2 = {
          labels: labelValues,
          //...
        };
        //Insert your logic here to handle data2
    }
});