2014-10-01 36 views
0

我很新的Javascript。我有一些問題,我的劇本 事情我通過$不用彷徨不得不循環,我陷在一個循環這裏是我的代碼

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"] 

    for (var i = 0; i < a.length; i+=1){ 
     .$get('url' + "?params=" + a[i],function(data2){    
      school = data2['data']; 
     }); 
    } 

    console.log(school); 

當我試圖CONSOLE.LOG(學校),它一直顯示「對象{}「

如何獲得外部循環數據?

如果你能幫助我解決這個問題,我將不勝感激。

謝謝。

+2

歡迎的奇妙世界** **異步!你不能那樣做。 – SLaks 2014-10-01 19:40:14

回答

1

你必須使用回調函數或類似的東西。

因爲$不用彷徨是異步功能,當

console.log(school); 

執行(!),學校還沒有評估。

你可以使用這樣的一些東西。

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"] 

    for (var i = 0; i < a.length; i+=1){ 
     .$get('url' + "?params=" + a[i],function(data2){    
      school = data2['data']; 
      console.log(school); 
     }); 
    } 

a = ["{"sid":"13485"}","{"sid":"25114"}","{"sid":"45145"}"] 
var school ={}; 
for (var i = 0; i < a.length; i+=1){ 
    .$get('url' + "?params=" + a[i],function(data2){    
     school = data2['data']; 
     whenitready(); 
    }); 
} 

function whenitready(){ 
    console.log(school); 
} 
0

如果您需要等到所有請求都做了,你需要的東西是這樣的:

var endpoints = []; 
for (var i = 0; i < a.length; i+=1) { 
    endpoints.push($.get('url' + '?params=' + a[i])); 
} 
$.when.apply($, endpoints).done(function() { 
    // Function arguments array differs if we have one or more than one endpoint. 
    // When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR]. 
    // When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...]. 
    // Normalize the single endpoint to the generic list one. 
    var args = endpoints.length > 1 ? arguments : [arguments]; 
    for (var i = 0; i < args.length; i++) { 
    var data = args[i][0]; 
    // Do stuff here with every data received... 
    school = ... 
    } 

    console.log(school); 
}); 
+0

Tans of Thanksssss !!!! 你的代碼太棒了! 它的作品! – MoleesMole 2014-10-01 20:36:50

相關問題