2016-11-30 72 views
0

我正在使用jquery get函數從服務器(Laravel應用程序)檢索數據。數據通常是一組對象。簡化.js代碼如下所示:將響應插入對象數組

$(function(){ 
    var results = []; 
    var getIt = function(){ 
     $.get('results', function(response){ 
      $.each(response, function(index, value){ 
       results.push(value); 
      }); 
     }); 
    }; 
    getIt(); 
    console.log(results.length); 
}); 

但控制檯記錄0,所以數組爲空; 它有什麼問題。該陣列應可用於以後的功能 。謝謝你的建議。

+0

'$ .get()'是異步的;你正在嘗試在交付之前吃披薩。查看我標記爲重複的問題以獲取更多詳細信息。 –

+0

謝謝大家的回答;我試圖尋找它,但方向不對;這聽起來更清楚了;謝謝; – BillCode

回答

0

在填充之前,您正在使用results陣列。您需要等待您的GET /results首先返回。假設你的代碼的其餘部分作品,下面的變化將console.log填充的數組:

$(function(){ 
    var results = []; 
    var getIt = function(){ 
     $.get('results', function(response){ 
      $.each(response, function(index, value){ 
       results.push(value); 
      }); 

      console.log(results.length); 
     }); 
    }; 
    getIt(); 
}); 
0

因爲$不用彷徨是異步的,results變量仍然是空當代碼調用。看看我的意思,試試這個:

$(function(){ 
    var results = []; 
    var getIt = function(){ 
     $.get('results', function(response){ 
      $.each(response, function(index, value){ 
       results.push(value); 
      }); 

      getIt(); 
      console.log(results.length); 
     }); 
    }; 


});`