简体   繁体   English

在使用$ .get()请求进行多维for循环后,如何触发事件?

[英]How to fire an event after a multi-dimensional for loop with $.get() requests?

I have two arrays chosen1 & chosen2. 我有两个数组selected1和selected2。 The items in these arrays are my $.get() properties that I send. 这些数组中的项目是我发送的$ .get()属性。 I am trying to render a Highcharts chart (called using the renderChart()) function once the loop is complete. 一旦循环完成,我将尝试渲染Highcharts图表(使用renderChart()进行调用)。 I tried multiple solutions and ended up with the code below. 我尝试了多种解决方案,并得到了下面的代码。 How do I listen for when all the $.get() requests are done so I can fire the Highcharts function on the page? 完成所有$ .get()请求后,我该如何侦听,以便可以在页面上触发Highcharts函数?

var chosen1         = [],
    chosen2         = [],
    computedSeries  = [],
    XHRs            = [];

function getData() {
    var rebuildingChart = '<div id="rebuilding-chart"><div id="floatingCirclesG"><div class="f_circleG" id="frotateG_01"></div><div class="f_circleG" id="frotateG_02"></div><div class="f_circleG" id="frotateG_03"></div><div class="f_circleG" id="frotateG_04"></div><div class="f_circleG" id="frotateG_05"></div><div class="f_circleG" id="frotateG_06"></div><div class="f_circleG" id="frotateG_07"></div><div class="f_circleG" id="frotateG_08"></div></div><p>Crunching Data</p></div>';

    $('#cc-chart').children().remove();
    $('#cc-chart').html(rebuildingChart);

    $(chosen1).each(function() {
        var fruits = this;
        $(chosen2).each(function() {
            var veggies = this;
            XHRs.push($.get("/fetchData", {fruit: fruits, veggie: veggies}, function(data) {
                var chartJSON       = data,
                    selectedKPI     = veggies,
                    singleSeries    = {},
                    KPIData         = [];

                for (var i = 0; i < chartJSON.length; i++) {
                    var point = [];
                    point.push(chartJSON[i]['utc_time']);
                    point.push(Math.round(chartJSON[i]['kpi_value']));
                    KPIData.push(point);
                };

                singleSeries["name"] = selectedKPI;
                singleSeries["data"] = KPIData;
                computedSeries.push(singleSeries);
            }));
        });
    });

    $.when(XHRs).then(function() {
        renderChart();
    });
}

$.when将deferreds作为参数时,如果要传递数组,则需要使用apply调用函数:

$.when.apply($, XHRs).then(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM