javascript 和 jsp
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4617667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript and jsp
提问by nikhil
when i try to access a jsp variable in javascript i always get it as null. why is this so? how do i get actual jsp variable value in javascript. here is my code
当我尝试在 javascript 中访问 jsp 变量时,我总是将其设为 null。为什么会这样?我如何在 javascript 中获取实际的 jsp 变量值。这是我的代码
<%! String oldpassword; %>
<html>
<head>
<script type="text/javascript">
function redirect()
{
var oldpassword_actual="<%= oldpassword %>";
var oldpassword_entered=document.form.oldpassword.value;
var newpassword=document.form.newpassword.value;
var reenterpassword=document.form.confirmpassword.value;
alert(oldpassword_actual);
alert(oldpassword_entered);
alert(newpassword);
alert(reenterpassword);
return false;
}
</script>
</head>
<body align="center">
<form name="form" action="" method="post">
Enter old password<input type="password" name="oldpassword"></br></br>
Enter new password<input type="password" name="newpassword"></br></br>
Reenter new password<input type="password" name="confirmpassword"></br></br>
<%
oldpassword=(String)session.getAttribute("Password");
%>
<input type="submit" name="confirm" value="Confirm" onclick="return redirect()">
</form>
</body>
</html>
when the alert box pops up..it gives a null value for the jsp variable..
当警告框弹出时..它为 jsp 变量提供了一个空值..
回答by BalusC
It's because the JSP variable is been printed as JavaScript variable beforethe form is submitted.
这是因为在提交表单之前,JSP 变量被打印为 JavaScript 变量。
Short explanation: JSP runs at webserver, produces HTML/CSS/JS, webserver sends it to webbrowser, HTML/CSS/JS runs at webbrowser. Long explanation: communication between Java/JSP and JavaScript.
简短说明:JSP 在 webserver 上运行,生成 HTML/CSS/JS,webserver 将其发送到 webbrowser,HTML/CSS/JS 在 webbrowser 上运行。详细解释:Java/JSP 和 JavaScript 之间的通信。
How to solve this: replace JavaScript by a Java Servlet. JavaScript isn't the right tool for the job of request processing.
如何解决这个问题:用Java Servlet替换 JavaScript 。JavaScript 不是用于请求处理工作的正确工具。
回答by John Kurlak
You need to move:
你需要移动:
<%
oldpassword=(String)session.getAttribute("Password");
%>
To the top of your code (or somewhere above the line: var oldpassword_actual="<%= oldpassword %>";)
到代码的顶部(或该行上方的某处:var oldpassword_actual="<%= oldpassword %>";)

