Javascript 将Java数组从SpringMVC控制器传递到JSP脚本变量引发错误
背景故事:我正在创建一个网页,以条形图格式显示整个月服务器的每日访问次数 库/技术:Javascript 将Java数组从SpringMVC控制器传递到JSP脚本变量引发错误,javascript,java,spring,jsp,Javascript,Java,Spring,Jsp,背景故事:我正在创建一个网页,以条形图格式显示整个月服务器的每日访问次数 库/技术: Spring Boot-用于MVC后端 .JSP-用于实际网页布局 D3JavaScript-用于创建图形元素 Tomcat-为了整个混乱的运行 因此,我在页面控制器中的一个整数数组中收集了数据,并将其传递给JSP页面脚本部分中的一个变量。我遇到的问题是,如果我将.JSP作为int数组传递,它会抛出一个“非法字符”错误;如果我作为字符串数组传递,它会抛出“元素列表后缺少]字符”错误 在这一点上,具体的错误对
- Spring Boot-用于MVC后端
- .JSP-用于实际网页布局
- D3JavaScript-用于创建图形元素
- Tomcat-为了整个混乱的运行
//converting from list to array and translating to string if int array is impossible
index = 0;
String[] graph1Data = new String[dailyCount.size()];
for(int i : dailyCount) {
graph1Data[index] = dailyCount.get(index).toString();
log.info(index + " = " + graph1Data[index]);
index++;
}
//passing data to the JSP page
mav.addObject("serverName", serverInstance.getName());
mav.addObject("month",month);
mav.addObject("hostItems", hostItems);
mav.addObject("totals", totalItems);
mav.addObject("graph1Data", graph1Data);
return mav;
这是我获取传递的数据并尝试将其分配给脚本变量的代码
//java script code above
document.getElementById("defaultOpen").click();
var src = ${graph1Data}); //<<-- attempting to assign to script variable
var msvg = d3.select("#mGraph"),
margin = 100,
width = msvg.attr("width") - margin,
height = msvg.attr("height") - margin;
var data = [10, 50, 15, 30, 20]; //<<-- what the passed data will replace
//more D3 graphing code below
//上面的java脚本代码
document.getElementById(“defaultOpen”)。单击();
var src=${graph1Data})// 是否可以从控制器传递列表而不是数组?在这种情况下,toString()方法的整数列表将生成与javascript数组具有相同语法的字符串
对于字符串列表,需要为每个字符串添加引号,以实现与javascript中相同的语法。例如:
String[] graph1Data = new String[dailyCount.size()];
for(int i : dailyCount) {
// adding quotation marks
graph1Data[index] = "'" + dailyCount.get(index).toString() + "'";
log.info(index + " = " + graph1Data[index]);
index++;
}
// convert array to list when adding it to model-and-view
mav.addObject("graph1Data", Arrays.asList(graph1Data));
在这种情况下,Thymeleaf(它理解JS脚本,可以像这样清晰地进行内联)比JSP更容易使用。@chrylis onstrike-希望我可以切换,但这是一个工作项目,所以我在这件事上没有太多选择