从多个$ .get调用创建数组

时间:2012-03-27 19:42:09

标签: javascript jquery ajax google-visualization

我正在尝试填充将用于传递到Google Visualizations API

的javascript数组

我有多个包含简单库存数据的表,数组的每个元素都会从一个表中保存一些信息。到目前为止,这就是我填充数组的方法

function drawMapOfPortfolio(symbols, chart_div) {
var gdata = new google.visualization.DataTable();
gdata.addColumn('string', 'Symbol');
gdata.addColumn('string', 'Sector');
gdata.addColumn('number', 'Volume');
gdata.addColumn('number', 'Percent Change');
gdata.addRow(["Portfolio", null, 0, 0]);
gdata.addRow(["Information Technology", "Portfolio", 0, 0]);
gdata.addRow(["Financials", "Portfolio", 0, 0]);
gdata.addRow(["Consumer Staples", "Portfolio", 0, 0]);
gdata.addRow(["Consumer Discretionary", "Portfolio", 0, 0]);

//setup arrays to store the XHR objects to resolve
//and to store the data returned from the server for each request
var jqXHRs = [],
data = [];

//your loop will run faster if you cache the length of the array
for(i=0, len = symbols.length; i < len; i++) {
    //create an IIFE to save the state of the `i` variable for each callback function
    //IIFE = Immediately-Invoked-Function-Expression
    (function (i) {
        var symbol = symbols[i];
        jqXHRs[i] = $.ajax({
            url: "mysql_api.php", 
            type: "GET",
            data: { sqlquery: "SELECT volume, day_change_percent, sector FROM " + symbol + " LEFT JOIN sector USING(symbol) ORDER BY unixTS DESC LIMIT 1" },
            dataType: "json",
            success: function(serverResponse) {
                var treemapData = [symbol, serverResponse[0]["sector"], parseFloat(serverResponse[0]["volume"]), parseFloat(serverResponse[0]["day_change_percent"])];
                data[i] = treemapData;
            }
        });
    })(i);
}

//when all the XHR objects resolve, add their server responses to your `gdata` object
$.when(jqXHRs).then(function () {
    gdata.addRows(data);
    alert(data);
    var chart = new google.visualization.TreeMap(document.getElementById(chart_div));
    chart.draw(gdata, {
    minColor: '#f00',
    midColor: '#ddd',
    maxColor: '#0d0',
    headerHeight: 15,
    fontColor: 'black',
    showScale: true
    });
});

}

但为了做到这一点,我必须将异步设置为false。通过将async设置为true,将发出查询,并且Google可视化将尝试在填充数组之前绘制图表。这有什么办法吗?我想我要找的是

使用async $ .ajax调用来填充数组,但在调用Google Visualization的绘图函数之前等待所有内容同步。

更新:更改了javascript代码,但$ .when

中的“data”数组为空

1 个答案:

答案 0 :(得分:1)

//setup arrays to store the XHR objects to resolve
//and to store the data returned from the server for each request
var jqXHRs = [],
    data   = [];

//your loop will run faster if you cache the length of the array
for(i=0, len = symbols.length; i < len; i++) {

    //create an IIFE to save the state of the `i` variable for each callback function
    //IIFE = Immediately-Invoked-Function-Expression
    (function (i) {
        var symbol = symbols[i];
        jqXHRs[i] = $.ajax({
            url      : "mysql_api.php", 
            type     : "GET",
            data     : { sqlquery: "SELECT volume, day_change_percent, sector FROM " + symbol + " LEFT JOIN sector USING(symbol) ORDER BY unixTS DESC LIMIT 1" },
            dataType : "json",
            success  : function(serverResponse) {
                var treemapData = [symbol, serverResponse[0]["sector"], parseFloat(serverResponse[0]["volume"]), parseFloat(serverResponse[0]["day_change_percent"])];

                //add the server response from this request to the same index as the XHR object for this request
                data[i] = treemapData;
            }
        });
    })(i);
}

//when all the XHR objects resolve, add their server responses to your `gdata` object
$.when(jqXHRs).then(function () {
    for (var i = 0, len = data.length; i < len; i++) {
        gdata.addRow(data[i]);
    }
});

严厉警告

您正在将完整的SQL查询传递到服务器端脚本中。这是非常不安全的,因为我可以使用我的开发人员控制台粘贴我想要运行的任何SQL。例如,我可以很容易地删除整个数据库...