2014-02-16 28 views
0

我有一個全球性的array我想console.log(array_name),但我得到了一個未定義的錯誤 下面是我的代碼:JavaScript的全局數組不能登錄

<script type="text/javascript"> 
var profit = []; 
$(document).ready(function(e) { 
    $.ajax({ 
     url : "/php/get-inflow.php", 
     dataType: "json", 
     type: "POST", 
     success: function(data){ 
      for(var i =0; i<data.length; i++){ 
       if(data[i] == null){ 
        profit[i] = 0; // logging profit[i] here gives me correct value 

       }else{ 
        profit[i] = parseInt(data[i]); // logging profit[i] here gives me correct value 
       } 
      } 
     } 
    }); 
    console.log(profit); 
      //some other functions....... 
    }); 
</script> 

當我看到控制檯我得到的輸出[ ]這意味着一個空白陣列......

是否將利潤數組正確設置爲全局(新的jquery) 如何訪問全局數組和其他函數 謝謝!

+3

ajax是異步的,這是你的'問題'在這裏 –

回答

0

約翰格林說的一個例子(標記約翰格林是正確的!) - 這太大了,不能評論。

var profit =[]; 
function logresults(data) { console.log(data); } 

$(document).ready(function(e) { 


    function _ajax(callback) { 

     $.ajax({ 
      url : "/php/get-inflow.php", 
      dataType: "json", 
      type: "POST", 
      success: function(data){ 
       for(var i =0; i<data.length; i++){ 
        if(data[i] == null){ 
         profit[i] = 0; 

        }else{ 
         profit[i] = parseInt(data[i]); 
        } 

       } 
       callback(profit); 
      } 
     }); 

    } 

    /* run */ 
    _ajax(logresults); 

}); 
1

AJAX異步運行。 'profit'將在您的'成功'關閉中有一個值,但不會立即跟在通話之後。

如果您確實需要,您還可以同步運行您的AJAX調用(爲async添加一個選項:false)。這會阻止你的網頁做任何事情,直到交易完成。