在同一个jsp上从javascript访问java变量 [英] Accessing java variable from javascript on same jsp

查看:126
本文介绍了在同一个jsp上从javascript访问java变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<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>

在eclipse中我收到错误

In eclipse I am getting an error

myVar cannot be resolved to a variable


推荐答案

由于您尝试使用未定义的变量,因此无效。代码生成如下:

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>

仍然,使用scriptlet 非常气馁。假设您正在使用 JSTL 表达语言(EL),这可以改写为:

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

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

如果您的变量中包含等字符那么这种方法就会失败。你可以通过JSTL使用< c:out> 来逃避结果:

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

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

更多信息:

  • How to avoid Java code in JSP files?

这篇关于在同一个jsp上从javascript访问java变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆