将变量从 JSP 传递给 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17727137/
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
Passing variable from JSP to Javascript
提问by CIOC
I know there is already questions about that, but I just can′t simply get this work, I have a JSP file with a java variable in it:
我知道已经有问题了,但我不能简单地完成这项工作,我有一个带有 java 变量的 JSP 文件:
String test = "Hello";
String test = "Hello";
And I need to read this value in the Javascript embedded in the same JSP file, I tried so many options, but it is not working, and for security I don't want pass the value using the URL or hidden values.
我需要在嵌入在同一个 JSP 文件中的 Javascript 中读取这个值,我尝试了很多选项,但它不起作用,为了安全起见,我不想使用 URL 或隐藏值传递值。
Any ideas of how get this working?
有关如何使其工作的任何想法?
回答by vlio20
I know this one is old, but this worked for me:
我知道这个是旧的,但这对我有用:
var javaScriptVar="<%out.print(javaString);%>";
you need to make sure that if you are using an external js file (out of the jsp file), the above line has to be before the "include" script tag. for example this is the jsp file:
您需要确保如果您使用的是外部 js 文件(在 jsp 文件之外),上面的行必须在“include”脚本标记之前。例如这是jsp文件:
var javaScriptVar="<%out.print(javaString);%>";
<script src="some_location/test.js"></script>
回答by Hyman
The best way to do it is to use something like following in your javascript code;
最好的方法是在您的 javascript 代码中使用如下内容;
var myvar = '${jspvar}';
回答by deeban
You can pass the value by calling some methods in html part..
您可以通过调用 html 部分中的一些方法来传递值..
<input type="submit" value="view" onclick="callpro('<%= varname %>')" />
回答by dbanet
var jsvariable="<%=test%>";
回答by thevangelist
One thing to note is that you could namespace those variables in this way:
需要注意的一件事是,您可以通过这种方式命名这些变量:
var MYAPP.javaScriptVar="<%out.print(javaString);%>";
var MYAPP.javaScriptVar="<%out.print(javaString);%>";
The technique is from "Javascript: The Good Parts" Book.
该技术来自“Javascript: The Good Parts”一书。