2014-10-26 148 views
-1

我正在使用下面的代碼片斷將double數組的java數組返回給另一個javascript函數。從javascript函數返回一個值

var getCredits = (function() { 
    console.log('Getting credits'); 
    $.ajax({ 
     type : 'GET', 
     url : rootURL+"/getCredits", 
     dataType : "json", // data type of response 
     success : function(data){ 
      var array = []; 
      console.log('Credits data = '+data); 
      for(var x in data){ 
       console.log('x = '+data[x]); 
       array.push(data[x]); 
      } 
      console.log('credits array is '+array); 
      return array; 
     } 
    }); 
}); 


var getDebits = (function() { 
    var myArray = [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]; 
    console.log('debits array is '+myArray); 
    return myArray; 
}); 

當我運行的代碼 - 日誌以下 -

「我的生成圖形」 myMain.js:110 「獲得信用」 myMain.js:149 「借記陣列是3.9, 4.2,5.7,8.5,11.9,15.2,17,16.6,14.2,10.3,6.6,4.8「 myMain.js:169」Credits Credits = 10.7,20.5「myMain.js:156」x = 10.7「 myMain.js :158「x = 20.5」myMain.js:158「學分數組是10.7,20.5」

the getD ebit功能基本上就是我想要的getCredits功能。 從它看起來像它的什麼,我想日誌 - 但我將其傳遞到另一個函數,它看起來像 -

var generateMyGraph = (function() { 
    console.log("generating my graph"); 
    $('#myLineGraph').highcharts({ 
     chart: { 
      type: 'line' 
     }, 
     title: { 
      text: 'Finances per month' 
     }, 
     subtitle: { 
      text: 'Credit and Debit per month' 
     }, 
     xAxis: { 
      categories: ['Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug','Sep','Oct'] 
     }, 
     yAxis: { 
      title: { 
       text: 'Euro (€)' 
      } 
     }, 
     plotOptions: { 
      line: { 
       dataLabels: { 
        enabled: true 
       }, 
       enableMouseTracking: true 
      } 
     }, 
     series: [{ 
      name: 'Credit', 
      data: getCredits() 
     }, { 
      name: 'Debit', 
      data: getDebits() 
     }] 
    }); 
}); 

和它不工作,任何想法?提前致謝!

+0

看起來像着名的dup http://stackoverflow.com/quest離子/ 14220321 /如何對返回的響應-從-AN-Ajax的呼叫 – elclanrs 2014-10-26 21:39:35

回答

1

由於ajax調用異步獲取來自服務器的響應,您不能從ajax調用返回值,但可以在響應到達時調用函數。

因此,而不是試圖返回值:

return array; 

呼叫需要這些數據的功能和傳遞數據,因爲在這個時候,你需要的數據是可用的:

generateMyGraph(array); 

然後調整您的功能以接收和使用此數據:

var generateMyGraph = (function(arrData) { //<=== local alias to 'array' 
//.... 
    series: [{ 
     name: 'Credit', 
     data: arrData //<===== use data here 
    }, { 
//......