2013-10-17 169 views
1

我需要將一個java變量傳遞給javascript函數。我有我的代碼如下。想知道是正確的方法嗎?將java變量傳遞給javascript函數

因爲在第一次加載頁面並點擊按鈕時,我遇到了一些問題,chartData和categories是空的。

我期待下面的:

chartData = [{"name":"Anne","data":[1.0,0.0,4.0]}, 
      {"name":"Billy","data":[5.0,7.0,10000.0]}] 
categories = ["APPLES","BANANAS","ORANGES"] 

public String doLoadChartDataAction() { 

    String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]"; 
    String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]"; 

    System.out.println("1.0 " + " _cat:" + _cat); 
    System.out.println("1.0 " + " _data:" + _data); 

    setCategories(_cat); 
    setChartData(_data); 

    return "";  
} 


<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}" 
    oncomplete="renderChart('container','line','Sample Chart','${pc_Test.chartData}', '${pc_Test.categories}');"> 
</p:commandButton> 
+0

我認爲當你加載頁面,你可以做一個AJAX調用您的服務器端,然後服務器(JAVA)返回你想要的數據;在你的javascript中,你可以使用這些數據進行處理。即java文件返回你一個json對象和回調處理使用json對象.. – Robin

+0

@Robin是正確的你想要一個json對象形式java然後在javascript中處理 – BholaVishwakarma

+0

@Robin感謝您的意見。我設法用下面的修改代碼來解決這個問題。 (: – bittersour

回答

1
public String doLoadChartDataAction() { 

String _cat = "[{\"name\":\"Anne\",\"data\":[1.0,0.0,4.0]},{\"name\":\"Billy\",\"data\":[5.0,7.0,10000.0]}]"; 
String _data = "[\"APPLES\",\"BANANAS\",\"ORANGES\"]"; 

System.out.println("1.0 " + " _cat:" + _cat); 
System.out.println("1.0 " + " _data:" + _data); 

//setCategories(_cat); 
//setChartData(_data); 

RequestContext context = RequestContext.getCurrentInstance(); 
context.addCallbackParam("chartData", _data); 
context.addCallbackParam("categories", _cat); 

return "";  
} 

<p:commandButton styleClass="commandButton" value="This" id="btnThis" action="#{pc_Test.doLoadChartDataAction}" 
oncomplete="renderChart('container','line','Sample Chart', args.chartData, args.categories);">