2014-03-18 26 views
-3

我收到這樣的JSON對象(擡頭通過Chrome瀏覽器開發工具): JSON Array如何將JSON對象轉換爲JavaScript數組?

我怎麼能簡單地分配(或轉換),它的變種? 我的意思是,我想它成爲: VAR ARR = [10,11,12,13,14,15]

更多信息 - 這JSON對象當屬從servlet AJAX響應:

編輯:

這是現在的樣子:

$(document).ready(function(){ 
      var rrr = []; 

      $.ajax({ 
       url: 'DataProvider', 
       type: "get", 
       dataType: 'json', 
       success: function(response) { 
        rrr = response; 
        console.log(+rrr); //output: [10, 11, 12, 13, 14, 15] 
       } 
      }); 

      console.log(rrr); //output: [] - why is the array empty here??? 

      var ctx = $('#myChart').get(0).getContext("2d"); 

      var data = { 
       labels : ["Roll 1","Roll 2","Roll 3","Roll 4","Roll 5","Roll 6"], 
       datasets : [ 
        { 
         fillColor : "rgba(210,220,220,0.5)", 
         strokeColor : "rgba(220,220,220,1)", 
         data : rrr 
        } 
       ] 
      } 
      var myNewChart = new Chart(ctx).Bar(data); 
     }); 
+2

它已經是一個數組了。什麼「這不行」是什麼意思? – zerkms

+0

當您嘗試分配它時會發生什麼?你有錯誤信息嗎?是什麼讓你覺得它不起作用? –

+0

以上應該很好,爲什麼沒有它 – tymeJV

回答

3

我打算做一個猜測,你想使用的日期是準備好之前。你可能會嘗試使用回調函數將數據傳遞迴程序中的某一點,以便使用它。

function getData(callback) { 
    $.ajax({ 
    url: 'DataProvider', 
    type: "get", 
    dataType: 'json', 
    success: function(response) { 
    callback(response); 
    } 
    }); 
} 

getData(function (data) { 
    Chart.init(data); // or whatever you need to do with the data 
}); 

由於$.ajax使用承諾的界面,你也可以這樣做:

function getData() { 
    return $.ajax({ 
    url: 'DataProvider', 
    type: "get", 
    dataType: 'json' 
    }); 
} 

getData().then(function (data) { 
    Chart.init(data); // or whatever you need to do with the data 
}); 
1
$(document).ready(function(){ 
    var rrr = []; 
    $.ajax({ 
      url: 'DataProvider', 
      type: "get", 
      dataType: 'json', 
      success: function(response) { 
       rrr = response; 
       console.log(+rrr); //output: [10, 11, 12, 13, 14, 15] 
      } 
     }); 

     console.log(rrr); //output: [] - why is the array empty here??? 
     //Because the above function didn't get executed yet. 
     //(code snipped) 
    }); 
} 

這樣做:

$.ajax({ 
    url: 'DataProvider', 
    type: "get", 
    dataType: 'json', 
    success: function(response) { 
     rrr = response; 
     console.log(+rrr); //output: [10, 11, 12, 13, 14, 15] 
     itWorkedSoYouCanNowDoYouStuffNow(); 
    } 
}); 
function itWorkedSoYouCanNowDoYouStuffNow() { 
    console.log(rrr); //output: [10, 11, 12, 13, 14, 15] 
} 
-2

感謝安迪 - 我找到了解決方案。

只需簡單地添加:

async: false, 

到$就性能。

+2

爲什麼要在請求通過時延遲所有的JavaScript?異步回調是JS的一個強大功能。 – bjb568

+1

請參閱下面的答案,並且很抱歉在之前的評論中含糊不清。'異步:錯誤'是頭向imo的錯誤方式。 – Andy