What is the best way to use context-param in JavaScript
In my web.xml I set context param "pathToImages". In my jsp files to get path to my i开发者_如何学Gomages files I use EL, like this:
<img src="${initParam.pathToImages}"/image.jpg" />
But I have problem with JavaScript. In my js files I have code:
setInnerHTML("somePlace", "<.img src='images/s.gif'>");
I know this isn't beautiful code but it isn't mine :) I cannot get my pathToImages in the same way like from jsp. What is the best way to do this?
Pass it as parameter to the js function: function createImage(path) {..}
and invoke it with createImage('${initParam.pathToImages}')
Another, perhaps a better option is to have a js variable and initialize it with the desired value. In the JS file:
var imagePath;
function init(config) {
imagePath = config.imagePath;
}
and in your header:
init({imagePath: '${initparam.pathToImages}'});
If you are using templates to build your pages (i.e., tiles or velocity templates) you could assign the variable in your base template with a scriptlet, like:
<script> var imagePath = '<%= config.getServletContext().getInitParameter("pathToImages") %>'; </script>
Then you can refer to the imagePath variable in your js files.
Not pretty, but I don't believe there is a way to access the servlet context from a javascript file directly.
精彩评论