在同一个jsp上从javascript访问java变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18990700/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:07:37  来源:igfitidea点击:

Accessing java variable from javascript on same jsp

javajsp

提问by Vge Shi

Is it possible to access a String type variable defined in jsp from a javascript on the same page?

是否可以从同一页面上的 javascript 访问在 jsp 中定义的 String 类型变量?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">  
foo();
function foo()  
{  
var value = "<%=myVar%>";  
alert(value);   
}  
</script>  
</head>
<body>

<%

String myVar="blabla";
%>

</body>

</html>

In eclipse I am getting an error

在 Eclipse 中我收到一个错误

myVar cannot be resolved to a variable

采纳答案by Luiggi Mendoza

This won't work since you're trying to use an undefined variable. The code is generated like this:

这将不起作用,因为您正在尝试使用未定义的变量。代码是这样生成的:

... = myVar;
//...
String myVar = "blabla";

Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):

没有意义,对吧?因此,为了完成这项工作,您应该在使用变量之前声明它(一如既往):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTLand Expression Language(EL), this can be rewritten to:

尽管如此,非常不鼓励使用scriptlet 。假设您使用的是JSTL表达式语言(EL),则可以将其重写为:

<c:set name="myVar" value="blabla" />
<script type="text/javascript">  
    foo();
    function foo() {
        var value = "${myVar}";
        alert(value);
    }
</script>

If your variable has characters like "inside, then this approach will faile. You can escape the result by using <c:out>from JSTL:

如果你的变量有像"inside 这样的字符,那么这种方法将失败。您可以使用<c:out>from JSTL来转义结果:

var value = "<c:out value='${myVar}' />";

More info:

更多信息: