JS怎么获取JSP中Java的变量值
<html><head><title></title><scripttype="text/javascript">vars=<%=monSum%>;//这样获取不到值啊<...
<html>
<head>
<title></title>
<script type="text/javascript">
var s = <%=monSum%>;
//这样获取不到值啊
</script>
</head>
<body>
<%
int n = 1;
String url = "jdbc:mysql://localhost/personal";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,"root","123");
Statement stmt = null;
double[] monSum = new double[12];
ResultSet rs = null;
String time_year = (new SimpleDateFormat("yyyy")).format(new Date());
String time = "";
try{
while(n++<=12){
if(n<10){
time = time_year + "-0" + n;
}else{
time = time_year + "-" + n;
}
String sql = "select * from record where date like'"+time+"%'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
monSum[n] = monSum[n] + Double.parseDouble(rs.getString("cost"));
}
rs.close();
stmt.close();
}
}catch(SQLException e){
out.println(e.getMessage());
}
%>
</html> 展开
<head>
<title></title>
<script type="text/javascript">
var s = <%=monSum%>;
//这样获取不到值啊
</script>
</head>
<body>
<%
int n = 1;
String url = "jdbc:mysql://localhost/personal";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,"root","123");
Statement stmt = null;
double[] monSum = new double[12];
ResultSet rs = null;
String time_year = (new SimpleDateFormat("yyyy")).format(new Date());
String time = "";
try{
while(n++<=12){
if(n<10){
time = time_year + "-0" + n;
}else{
time = time_year + "-" + n;
}
String sql = "select * from record where date like'"+time+"%'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
monSum[n] = monSum[n] + Double.parseDouble(rs.getString("cost"));
}
rs.close();
stmt.close();
}
}catch(SQLException e){
out.println(e.getMessage());
}
%>
</html> 展开
展开全部
Java的变量值,理论上在js中是不能获取,但是可以通过间接的方式来获取。
提供两种思路供参考:
1、把java变量的值存在cookie中,js通过cookie去取;
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
var value= getCookie("cookie的name名");
2、把java变量的值赋值给页面中<input type="hidden"/>的value,通过js去取;
var value=document.getElementById("hidden的ID").value;
展开全部
<%=expression%>只会打印出expression的toString值,你这个monSum是个double[]的数组,应该使用
var s = <%=Arrays.toString(monSum) %>
var s = <%=Arrays.toString(monSum) %>
追问
依旧不行啊!monSum那儿还是报错
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
在java中这样写:request.setAttribute("monSum", monSum);
在js中获取:${monSum};
你这样试试看
在js中获取:${monSum};
你这样试试看
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
早上好!!
你的script脚本放在 java代码的下面试试···
你的script脚本放在 java代码的下面试试···
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询