2017-07-30 65 views
0

我有一個JSP頁面,裏面有一段我寫的JavaScript代碼,運行良好。我需要用thymeleaf重新編寫相同的代碼,但不起作用。 JSP的JavaScript代碼:如何在JavaScript代碼中使用thymeleaf?

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
<script type="text/javascript"> 
    google.charts.load('current', {'packages':['corechart']}); 

    google.charts.setOnLoadCallback(drawChartPie); 

    function drawChartPie() { 

    var data = google.visualization.arrayToDataTable([ 
     ['Conta', 'Valor'],   
     <c:forEach items="${model.contaCorretora }" var="contaCorretora"> 
     ['${contaCorretora.tipoConta}', ${contaCorretora.valorAtual}], 
    </c:forEach> 
     ]); 

    var options = { 
     title: '${model.pessoa.nome }' 
    }; 

    var chart = new google.visualization.PieChart(document.getElementById('piechart')); 

    chart.draw(data, options); 
    } 

</script> 

我沒有找到方法將此代碼遷移到百里香。

更新1:

我使用的代碼,你給我建議,但仍然不能正常工作:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">></script> 
<script type="text/javascript" th:inline="javascript"> 
/*<![CDATA[/ 
google.charts.load('current', {'packages':['corechart']}); 

    google.charts.setOnLoadCallback(drawChartPie); 

    var array = [[${investimento}]]; 

    function drawChartPie() { 

    var data = google.visualization.arrayToDataTable([ 
     ['Conta', 'Valor'],   
     for (i in array) 
     { 
     ['array[i].tipoConta', array[i].valorTotalDolar],  
     } 
     ]); 

    var options = { 
     title: 'Teste' 
    }; 

    var chart = new google.visualization.PieChart(document.getElementById('piechart')); 

    chart.draw(data, options); 
    } 

    /]]>*/ 
</script> 

回答

0

首先啓用JavaScript內嵌在th:inline

<script type="text/javascript" th:inline="javascript"> 

然後使用雙括號表達式插入對象:

var options = { 
    title: [[${model.pessoa.nome}]]; 
}; 

相反的foreach,你應該使用的事實,Thymeleaf(與傑克遜庫的幫助),可以將對象序列化到JSON:

var contaCorretora = [[${model.contaCorretora}]]; 
// "contaCorretora" is now a JavaScript object, 
// make an array out of it or what you want 
+0

和包裝JS在CDATA這樣的腳本/ * <[! CDATA [* /你的java腳本代碼/ *]]> */ – Elizabeth

+0

嗨,我寫過你喜歡你的建議,但仍然無效。我在做什麼不正確? –

+0

@MuriloGóesdeAlmeida有什麼不起作用? – holmis83