2

I'm trying to loop through a list of objects (some measurements data) using JSTL forEach tag in javascript and display the data by using Google Charts API. The code is showing as following. But looks something wrong. As I double checked, the data in the list of measurements objects works fine to pass to html in ${listOfMeasurements}, ${measurements.measTime}, ${measurements.measS1raw} and ${measurements.measS2raw}. But in the javascript block, the forEach code is not working to execute data.addRow() as expected. My guess is, I'm not using forEach correctly in my javascript code, so data.addRow() was not executed as expected. How can I fix it?

<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>
4

2 回答 2

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。

您可能想阅读BalusC关于此主题的博客条目

于 2013-07-24T18:22:30.160 回答
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>
于 2016-10-16T13:29:47.093 回答