如何传递变量到一个JS文件 [英] How to pass variables in to a JS file

查看:192
本文介绍了如何传递变量到一个JS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个简单的答案,但是这个进来的2个问题的形式。

I know there's an easy answer to this, but this comes in the form of 2 problems.

问题1:

在一个asp.net页面上,有这样一个JavaScript块:

In an asp.net page there is a javascript block like this:

<script type="text/javascript">
    function doSomethingRandom() {
        var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" />
    }
</script>

好了,这是问题的一个简化版本,但它应该是清楚的。我现在想在一个JS文件移到这个功能...但我不能让ASP:立即到JS

Ok, so it's a simplified version of the problem, but it should be clear. I now want to move this function in to a JS file...but I can't get the asp:Literal into the JS.

var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" />
<script src="myJSFile.js" />

...让我有些不舒服,有没有更好的办法?

...Makes me a little sick, is there a better way?

问题2:

类似的问题,但这次的第二个版本是这样的:

Similar problem, but this time the second version looks like this:

<asp:ScriptManagerProxy runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/tree/AttributeTree.js" />
    </Scripts>
</asp:ScriptManagerProxy>

但这次我不能切实把

But this time I can't realistically put the

var myVarToUse = <asp:Literal runat="server" ID="HackyLiteral" />

在它上面,因为用的ScriptManagerProxy有知道究竟在何处脚本文件会出现没有真正的方法。

above it because with the ScriptManagerProxy there's no real way of knowing exactly where the script file is going to appear.

所以,他们的问题!谢谢你。

So, them's the problems! Thanks.

推荐答案

我们使用的的 的RegisterStartupScript 方法注册一个带有初始化函数ClientScriptManager。我们的JavaScript文件只包含的功能,并通过的ScriptManager (在你的代码片段等)被加载。我们写了一个扩展方法的第(名为 JSStartupScript )与注册启动脚本,并在这一天我们code如下所示的末尾帮助:

We use the Page's RegisterStartupScript method to register initialization functions with the ClientScriptManager. Our Javascript files only contain functions and are loaded via ScriptManager (like in your snippet). We wrote an extension method for the Page (called JSStartupScript) that helps with registering the startup scripts and at the end of the day our code looks like the following:

<%
   Page.JSStartupScript(string.Format("initFeatureX({0}, {1}, {2});",
      AntiXss.JavaScriptEncode(ViewData.Property1),
      AntiXss.JavaScriptEncode(ViewData.Property2),
      AntiXss.JavaScriptEncode(ViewData.Property3)));
%>

这也符合的ScriptManager 取值 CompositeScript 收集相结合的伟大工程, LoadScriptsBeforeUI =假设置。

This also works great in combination with the ScriptManagers CompositeScript collection and LoadScriptsBeforeUI = false setting.

这篇关于如何传递变量到一个JS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆