将JSP Integer数组传递给javascript时遇到问题。 JSP数组已正确填充。我可以在JSP代码中正确呈现JSP数组的元素。但是,当我将JSP数组传递给我的javascript函数时,我的javascript代码中的值是未定义的。
JSP Code Snippet
....
<! This works correctly !>
<div class="col content-M">
<p>JSP Array Population Test</p>
${daynumbers[2]}
</div>
<! This does not work !>
<div class="col content-L">
<p>Pass a JSP Integer Array to setDayValues</p>
<script type="text/javascript">setDayValues(${daynumbers});</script>
<div id="columnchart_values"></div>
</div>
....
JavaScript代码段
var a = Array(6);
function setDayValues(values) {
a[0] = values[0];
a[1] = values[1];
a[2] = values[2];
a[3] = values[3];
a[4] = values[4];
a[5] = values[5];
}
function simpleColumnChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['1', a[0], 'blue'],
['2', a[1], 'blue'],
['3', a[2], 'blue'],
['4', a[3], 'blue'],
['5', a[4], 'blue'],
['6', a[5], 'blue']
]);
....
}
就像我说的那样,[x]在javascript中是一个unifined。
答案 0 :(得分:0)
我认为问题在于您理解$ {daynumbers}错误的方式。 $ {daynumbers}将返回什么?一个javascript数组?尝试console.log($ {daynumbers}),你会发现你的问题,因为你可以看到$ {daynumbers [0]}的值,你可能会返回一个javascript不理解的java数组对象,所以你可以尝试将$ {daynumbers}转换为json字符串,并解析它。
答案 1 :(得分:0)
The problem is that ${daynumbers}
is resulting in invalid JavaScript being sent to the client.
If you want to output the array of integers, use Arrays.toString
:
<script type="text/javascript">setDayValues(${Arrays.toString(daynumbers)});</script>
The client browser will see
<script type="text/javascript">setDayValues([1, 2, 3, 4, 5, 6]);</script>
...(with your actual values, of course), which is valid JavaScript defining an array with those entries.
Then in setDayNumbers
, there's no need to copy them, just use the array passed into setDayNumbers
:
function setDayNumbers(values) {
a = values;
}