Javascript array not initialized

好久不见. 提交于 2020-01-07 09:03:05

问题


I have a problem with javascript array when passing into another object array. I have tried everything I came out on net, but nothing is working.

Problem is in line when fetching data from api on dataValues[dataValues.length] = (v.potroseno_tekucine);. Its working with labelValues. When I alert data in loop its ok, but when it needs to be processed it looks like its undefined. But when I, for example, alert(dataValues.length) before var data, its working ok.

$(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);
});

Can anyone help me please? I have tried with push, slice, concat but nothing...


回答1:


Ajax calls are asynchronous... this mean the data will be set before getting any response from your ajax request.

In order to fix this, you need to create your data in the ajax success callback function:

$.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
    }
});


来源:https://stackoverflow.com/questions/31415601/javascript-array-not-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!