Dan wrote:
Excuse me if i'm being a bit thick here, but is it possible to
reference a server side variable within an embedded js source file.
For example, my test.js file contains
alert('<%=tmpVar%>');
and my aspx page contains:-
<script type="text/javascript" src="test.js">
This simple pops up an alert box containing <%=tmpVar%>, rather than
the actual value of my server side variable.
I can understand why it doesn't parse it to my test.js file.
Anyone got any suggestions on how i can do this? I don't really want to
have to include my javascript in my aspx header, due to maintenance
issues.
Thanks in advance for any suggestions.
You may use the fall-back segment of the <scriptelement for that. A
<scriptelement with src attribute set consists of two blocks:
1) the source file pointed by src
2) fall-back code between <scripttags for UAs without src support.
If src attribute is set is supported then anything between <scripttag
is automatically ignored but still available at run-time as
document.scripts[i].text
Because for many years already there is not a single UA w/o script src
support, the fall-back part left empty:
<script src="source.js"></script>
or used for some other purposes, say for copyright info:
<script src="source.js">
Copyright 2006 Acme, Inc.
</script>
Another use is exactly for your case: to provide session values for a
static library:
<script src="source.js">
{data1:"value1", data2:"value2"}
</script>
so on ASP/PHP it would be:
<script src="source.js">
<processing instructions>
</script>
Of course JSON format is much more convenient here, then the run-time
task as simple as:
// presuming this is the first script element on the page:
var params = eval(document.script[0].text);