7

Is it possible to embed <% ... %> tags in a javascript file and have it render the appropriate server-side code? How can this be done?

4 Answers4

14

The process is actually backwards from what you're thinking.

You create an *.aspx page that renders to a JavaScript file. You can then reference that *.aspx page in your <script> tag:

<script type="text/javascript" src="someJavaScript.aspx"></script>
Justin Niessner
  • 229,755
  • 35
  • 391
  • 521
  • What does the .aspx file look like? I almost got this to work, but the second .aspx file doesn't seem to be able to reference anything from the first. – Dave Cousineau Sep 22 '16 at 16:42
6

Yes, this is possible, but it would not be a JS file, it would be an aspx file with Javascript in it instead of html.

In your page, to refrence it you would do:

<script type="text/javascript" src="myPage.aspx"></script>
Chris Kooken
  • 29,979
  • 14
  • 79
  • 113
2

I'm going to make some assumptions on what you are trying to accomplish. Most likely you have a javascript file that needs access to some info on the server. Let's say you need some stuff from the session that if it were an aspx page you'd make it look something like

<script type="text/javascript">
var username = '<%= Session["username"] %>';
var account_num = '<%= Session["account_num"] %>';
</script>

obviously this won't work in a .js file since it never goes through the page lifecycle that an aspx page would be processed though. However, you don't need to transform your entire .js file into an .aspx page as some others might be suggesting. There are lots of other ways to expose that data to your js code. I'll list 2.

  1. emit the above <script> in your page response (perhaps using a <asp:ContentPlaceHolder />)
  2. create a webservice (could even be a simple .ashx) that returns the var username = ... or even better returns json
Al W
  • 7,008
  • 1
  • 17
  • 39
1

Yes, it's possible by simply making a regular web page that contains Javascript instead.

However, it might not behave like you expect. Javascript files are cached longer than pages. As the browser might not request the file from the server each time, your could would not be executed each time the file is used.

Guffa
  • 640,220
  • 96
  • 678
  • 956
  • there are lots of ways to make the browser grab it each request – Chris Kooken Jun 15 '11 at 20:39
  • Preventing cache can be a headache. There are headers you can add that work *most* of the time http://stackoverflow.com/q/49547/866236 but I've found some browsers still cache files. Adding a get parameter with a timestamp seems to work more reliably: . – Dan May 12 '14 at 21:40