简体   繁体   English

如何从`.js`文件访问服务器端上下文?

[英]How to access serverside context from `.js` file?

I have to move all my scripts into a separate .js file. 我必须将所有脚本移动到单独的.js文件中。 But I have wired the code in the client ( *.aspx ) file, with code such as 但是我已经用以下代码将客户端( *.aspx )文件中的代码连接起来了

<script>
var x=<%=ViewData["Key"];%>
</script>

I'm sure there will be an issue when I move that line to the js file as the server side context can't be accessed. 我敢肯定,当我将该行移到js文件时会出现问题,因为无法访问服务器端上下文。

How do I solve this issue? 我该如何解决这个问题?

最简单的方法是移动所有JS代码(这些变量分配除外)。

Effectively, the trick is dependency injection in javascript. 实际上,诀窍是javascript中的依赖项注入。 First, abstract the variables you are generating from server-side variables into parameters for your javascript methods and objects. 首先,将要从服务器端变量生成的变量抽象为javascript方法和对象的参数。 Then use a small amount of script in-page to setup the javascripts to run. 然后使用少量的脚本页内设置来运行JavaScript。

If you are dealing with a few rather static things (eg--some path names), another tactic is to create a javascript "configuration" object that is in a separate, server-generated script, that can be called by your other scripts as needed. 如果您要处理一些相当静态的内容(例如某些路径名),则另一种策略是在单独的服务器生成的脚本中创建一个javascript“配置”对象,该脚本可以由您的其他脚本调用为需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM