如何在javascript中嵌入JSTL forEach

时间:2013-07-24 18:14:08

标签: javascript jsp jstl

我正在尝试使用javascript中的JSTL forEach标记遍历对象列表(某些测量数据),并使用Google Charts API显示数据。代码显示如下。但看起来有些不对劲。当我仔细检查时,测量对象列表中的数据可以正常传递到${listOfMeasurements}${measurements.measTime}${measurements.measS1raw}${measurements.measS2raw}中的html。但是在javascript块中,forEach代码无法按预期执行data.addRow()。我的猜测是,我没有在我的javascript代码中正确使用forEach,因此data.addRow()未按预期执行。我该如何解决?

<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Date');
    data.addColumn('number', 'measurement1');
    data.addColumn('number', 'measurement2');
     <c:forEach items="${listOfMeasurements}" var="measurements">
        "data.addRow("
        +"${measurements.measTime}"+","
        +"${measurements.measS1raw}"+","
        +"${measurements.measS2raw}"+");"
        ;
     </c:forEach>

    var options = {
      title: 'Measurements'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);

  }
</script>

2 个答案:

答案 0 :(得分:2)

尝试这样

<c:forEach items="${listOfMeasurements}" var="measurements">
   data.addRow(${measurements.measTime},${measurements.measS1raw},${measurements.measS2raw});
</c:forEach>

否则您将在脚本中获得错误的代码,例如:

"data.addRow("+"measTimeValue-1"+","+"measS1raw-1"+","+"measS2raw-1"");";
"data.addRow("+"measTimeValue-2"+","+"measS1raw-2"+","+"measS2raw-2"");";
"data.addRow("+"measTimeValue-3"+","+"measS1raw-3"+","+"measS2raw-3"");";

...那是不正确的javascript。

混合JSP标记和Javascript的问题在于它们出现在两个不同的阶段。 JSP渲染是第一位的,因此所有html,css和javascript代码都只是另一个字符串。因此,在JSP渲染完成后,您只有HTML。

您可能需要阅读this blog entry关于此主题的BalusC

答案 1 :(得分:0)

这可能是替代解决方案......

function drawBasic() {

        var data = google.visualization.arrayToDataTable([
            ['Date', 'measurement1','measurement2']
            <c:forEach var="measurements" items="${listOfMeasurements}">
                ,[${measurements.measTime},${measurements.measS1raw},${measurements.measS2raw}]
            </c:forEach>
        ]);         

      var options = {
        title: 'Change title Acoordingly',
        chartArea: {width: '50%'},
        hAxis: {
          title: 'Change title Acoordingly',
          minValue: 0
        },
        vAxis: {
          title: 'Change title Acoordingly'
        }
      };

      var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

      chart.draw(data, options);
    }
</script>

<body><div id="chart_div"></div></body>