Saturday, February 5, 2011

Session

I have had success with assigning the session variable in a script block on the page markup, then using that variable in the external JavaScript source file.  Semi-psuedocode from the page and JS source follows, respectively:

In page markup:
...
<body ...>
    
<script type='text/javascript'>
        var sessionVarForJS = "<%= sessionVariable %>";
    
</script>
    
<script type='text/javascript' src='./js/externalJS.js'></script>
...

In externalJS.js:
...
    if (sessionVarForJS == "somethingDesired")
        doSomething(
"whatever");
...

Example::

You cannot in anyway get the session values in an external .js file. If you need to get the session values into javascript, the javascript has to be on the same page or you can declare a javascript variable that gets set with the session value on the aspx page and then use this variable in the external .js file. However you will need to first declare the variable and then write the code for including the external js file like this

<script language='javascript'>
var sessionVar = <%=Session("ABC")%>
</script>
<script type="text/javascript" src="./ext.js"></script>
 
///
 
Then inside ext.js you can use the variable sessionVar




No comments :

Post a Comment