[英]Writing JSTL code for JavaScript
我有一個獨立的JavaScript,可以繪制圖形。
<script type="text/javascript" src="/GraphicalPortlet-portlet/js/amcharts.js"></script>
<script type="text/javascript" src="/GraphicalPortlet-portlet/js/raphael.js"></script>
<script type="text/javascript">
var chart;
var chartData = [
{country:"Tâches",a:25}, //this is the chart data
{country:"UK",a:25},
{country:"Fran\u00E7ais ",a:25 } ];
window.onload = function() {
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
var graph = new AmCharts.AmGraph();
graph.labelText="[[value]]";
graph.valueField = "a";
graph.type = "column";
//some other components
var valAxis = new AmCharts.ValueAxis();
valAxis.stackType = "regular";
valAxis.gridAlpha = 0.1;
valAxis.axisAlpha = 0;
chart.addValueAxis(valAxis);
var catAxis = chart.categoryAxis;
catAxis.gridAlpha = 0.1;
catAxis.axisAlpha = 0;
catAxis.gridPosition = "start";
//this is the actual plotting of graph
chart.write("chartdiv");
}
我的問題
1)如何為該JS編寫JSTL代碼,以便其他JSP可以包含我的JSTL並為其繪制圖表。
2)如果客戶端需要發送數據而不使用我的虛擬數據。 我將如何處理並更改我的JSTL?
整個想法是,不同的JSP不應復制我的JS代碼。 相反,只需包含一個帶有此JS代碼的JSTL標簽襯里即可。
您的問題令人困惑。 看起來您正在將JSTL與其他東西混合使用。 請閱讀我們的JSTL Wiki頁面以了解其實際含義。
據我了解,功能要求是您需要向JavaScript提供服務器端變量。 這可以通過幾種方式來完成。
讓JSP將其打印為全局JS變量:
<script>var data = ${someDataInJSONFormat};</script>
${someDataInJSONFormat}
是由預處理servlet准備的:
request.setAttribute("someDataInJSONFormat", someDataInJSONFormat);
並讓您的JS在窗口加載時訪問它:
window.onload = function() { doSomethingWith(data); }
讓JS通過Ajax檢索它:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var data = eval('(' + xhr.responseText + ')'); doSomethingWith(data); } } xhr.open('GET', 'someServletURL', true); xhr.send(null);
其中someServletURL
是返回數據的servlet的URL:
response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(someDataInJSONFormat);
您可以使用Gson之類的JSON庫將Java對象轉換為JSON字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.