jQuery每个循环变量数据丢失

jQuery each loop variable data lost

本文关键字:数据 变量 循环 jQuery      更新时间:2023-09-26

在jQuery中的变量作用域有点问题,如果我在.each循环之外执行console.log,我会在$stockData上得到一个空数组,这是怎么回事?(如果我在.each中这样做,它运行得很好,每次添加值都会记录数组)

$(document).ready(function(){
    // stock data will contain all the merged data from the database and yahoo queries
    var $stockData = new Array();
    // get data from yahoo and merge with dbData, add to stockData array
    $.getJSON( "/get_portfolio.php", function(dbData) {
        $.each( dbData, function(index) {
            var stock = dbData[index]
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                crossDomain: true
            }).success(function(data){
                var quote = data.query.results.quote;
                $.extend(quote, stock);
                $stockData.push(quote);
            }); // end success
        });// end each
    }); // end getJSON
    console.log($stockData);
}); // end document.ready

当您调用时

$.getJSON( "/get_portfolio.php", function(dbData) { ... });

这部分:

function(dbData) { ... }

不会马上逃跑。JavaScript说:"哦,你做了一个http请求?我会保留你给我的这个函数,并在请求完成后运行它。"。您的代码的其余部分将继续运行,因此:

console.log($stockData);

将首先运行。所以这里的实际执行顺序是:

  1. 运行getJSON
  2. console.log运行
  3. HTTP请求完成,回调运行

将console.log放在getJSON块中,就在.each循环之后:

$(document).ready(function(){
    // stock data will contain all the merged data from the database and yahoo queries
    var $stockData = new Array();
    // get data from yahoo and merge with dbData, add to stockData array
    $.getJSON( "/get_portfolio.php", function(dbData) {
        var requestsDone = 0;
        $.each( dbData, function(index) {
            var stock = dbData[index]
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                crossDomain: true
            }).success(function(data){
                var quote = data.query.results.quote;
                $.extend(quote, stock);
                $stockData.push(quote);
                if(++requestsDone == dbData.length) done();
            }).error(function(){
                if(++requestsDone == dbData.length) done();
            });
        });// end each
        function done() {
            console.log($stockData); // put this here
        }
    }); // end getJSON
}); // end document.ready

您需要等待getJSON函数完成,请尝试以下操作:

$(document).ready(function(){
    // stock data will contain all the merged data from our database and yahoo queries
    var $stockData = new Array();
    // get data from yahoo and merge with dbData, add to stockData array
    $.getJSON( "/get_portfolio.php", function(dbData) {
        $.each( dbData, function(index) {
            var stock = dbData[index]
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                crossDomain: true
            }).success(function(data){
                var quote = data.query.results.quote;
                $.extend(quote, stock);
                $stockData.push(quote);
            }); // end success
        });// end each
        console.log($stockData);
    }); // end getJSON
});