开发者

Using ASP.Net tags in a .js file?

Is it possible to embed <% ... %> tags in a javascript file and have it render the appropriate server-side code? How can this be don开发者_运维问答e?


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>


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>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜