I have a javascript file, where I have collected login- and other user profile ajax calls that needs to be available on all of the pages in my web application.
For all of my ajax calls, I need the context path of the webapp to get the correct URL. A baseUrl-variable can be defined by var baseUrl = "${pageContext.request.contextPath}";
.
I am experiencing a puzzling error though. If i try to initialize the baseUrl variable inside my login.js
-file, it does not work. It is simply set to the string value "${pageContext.request.contextPath}"
This .js-file contains all the scripts where I actually need the variable. However, if I define it inside a sourceless script-tag in the .jsp file itself, it works like a charm. (Code in the bottom)
I am guessing that this has something to do with when, and in which scope the expression is compiled and/or executed, and maybe also the difference between dynamic and static imports of code. I just can't wrap my head around exactly what is happening, and why my desired approach, to define the variable within the login.js
-file, does not work.
Working import statement:
<script>var baseUrl = "${pageContext.request.contextPath}";</script>
<script src="<c:url value="/js/login.js"/>" type="text/javascript"></script>
See Question&Answers more detail:os