2013-11-15 34 views
0

我發現了問題,但是我的解決方案不起作用。變量d0和d1被填充,但在代碼創建並拼接數組storelocations之後。因此,我得到一個錯誤,d0和d1未定義。任何解決方案JSON javascript未定義變量問題

的Javascript:

$(function() { 


     $.get("/Map/GetJsonData", function (data) { 
      storeLocations = []; 
      var d0 = data[0].Delay; 
      var d1 = data[1].Delay; 


     }); 

     var storeLocations = new Array(); 
     storeLocations.splice(storeLocations.length, 0, d0); 
     storeLocations.splice(storeLocations.length - 1, 0, d1); 


} 

回答

1

AJAX是異步,可以創建一個回調或者你需要的AJAX回調裏面是什麼:

$.get("/Map/GetJsonData", function (data) { 
     storeLocations = []; 
     var d0 = data[0].Delay; 
     var d1 = data[1].Delay; 

     var storeLocations = new Array(); 
     storeLocations.splice(storeLocations.length, 0, d0); 
     storeLocations.splice(storeLocations.length - 1, 0, d1); 
}); 
1

既然你聲明的變量(D0和d1)在$ .get方法的回調函數中,那些變量是私有的,並且只能在該函數聲明的行後面訪問。因此,您應該將storeLocations代碼移到回調函數中。

$(function() { 


    var storeLocations = new Array(); 
    $.get("/Map/GetJsonData", function (data) { 
     storeLocations = []; 
     var d0 = data[0]; 
     var d1 = data[1]; 


     storeLocations.splice(storeLocations.length, 0, d0); 
     storeLocations.splice(storeLocations.length - 1, 0, d1); 

    }); 
}); 

在我的例子,我宣佈storeLocations的$不用彷徨方法的範圍之內,因此這將是jQuery的文件準備好方法範圍(即它被宣佈上線後)內的任何地方訪問。

+0

是不是在外部功能舉行的範圍? – Zlatko