最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pass JSP value to external Javascript file - Stack Overflow

programmeradmin3浏览0评论

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:

JSP

String str = "Hello";

external.js

//not working
var str = "<%=str%>";

Thanks.

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:

JSP

String str = "Hello";

external.js

//not working
var str = "<%=str%>";

Thanks.

Share Improve this question asked Jul 7, 2011 at 9:45 user200340user200340 3,37113 gold badges55 silver badges77 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

If you think that the java script is written inside the JSP then its possible.

But you are providing the JS file separately then you can make a global variable and that variable will be available everywhere.

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.

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:

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:

<action name="foo"><result>foo.jsp</result></action>

home.jsp:

<script type="text/javascript" src="foo.action" charset="UTF-8"></script>

Define the string before you include the JavaScript file in your JSP file.

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

e.g.

alert(str) 
发布评论

评论列表(0)

  1. 暂无评论