将 JSP 值传递给外部 Javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6608644/
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
Pass JSP value to external Javascript file
提问by user200340
Is there a way that I can pass a JSP variable value to an external Javascript file by using only Javascript and JSP. Something like:
有没有办法只使用 Javascript 和 JSP 将 JSP 变量值传递给外部 Javascript 文件。就像是:
JSP
JSP
String str = "Hello";
external.js
外部.js
//not working var str = "<%=str%>";
Thanks.
谢谢。
采纳答案by Talha Ahmed Khan
If you think that the java script is written inside the JSP then its possible.
如果您认为 java 脚本是在 JSP 中编写的,那么它是可能的。
But you are providing the JS file separately then you can make a global variable and that variable will be available everywhere.
但是您单独提供 JS 文件,然后您可以创建一个全局变量,该变量将随处可用。
回答by Kevin Bowersox
Your not going to be able to write to the external js file. However if you put var s = "<%=str%>";
in your jsp s will become a global variable which can be used within your external js file because s will have a global scope. So in a nutshell, you can't modify the actual js file, but you can add a variable with global scope and reference that variable within your external js script.
您将无法写入外部 js 文件。但是,如果您放入var s = "<%=str%>";
jsp s 将成为可以在外部 js 文件中使用的全局变量,因为 s 将具有全局范围。所以简而言之,你不能修改实际的 js 文件,但你可以添加一个具有全局范围的变量,并在你的外部 js 脚本中引用该变量。
回答by daveoncode
You can just create a jsp containing js code with "dynamic stuff" printed inside and then import that jsp as a normal js file. I'm gonna show you my own implementation, for the site where I'm working on (it makes use of struts). I'm using this approach to export to the client side a map containing several localized strings:
您可以创建一个包含内部印有“动态内容”的 js 代码的 jsp,然后将该 jsp 作为普通 js 文件导入。我将向您展示我自己的实现,用于我正在工作的站点(它使用了 struts)。我正在使用这种方法将包含多个本地化字符串的地图导出到客户端:
foo.jsp:
foo.jsp:
<%@ page contentType="text/javascript" pageEncoding="UTF-8" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
var myString = '<s:text name="foo.MY_STRING" />'
struts.xml:
struts.xml:
<action name="foo"><result>foo.jsp</result></action>
home.jsp:
主页.jsp:
<script type="text/javascript" src="foo.action" charset="UTF-8"></script>
回答by Yilei
Define the string before you include the JavaScript file in your JSP file.
在 JSP 文件中包含 JavaScript 文件之前定义字符串。
<script type="text/javascript">
var str = "Hello";
</script>
<script src="js/myJavascript.js"></script>
In your JavaScript file, you can directly refer to the variable.
在您的 JavaScript 文件中,您可以直接引用该变量。
e.g.
例如
alert(str)