如何将变量值后面的代码绑定到javascript

How to bind code behind variable value to javascript?

本文关键字:代码 绑定 javascript 变量值      更新时间:2023-09-26

我有一个javascript头<script type="text/javascript" src="http://example.com?Key=">Key位于类似string Key="123456";的aspx.cs中。如何将此Key值绑定到javascript标头?

您可以访问aspx文件中的代码隐藏变量:

<script type="text/javascript" src="http://example.com?Key=<%= Key %>">

试试这个方法:

1-通过添加id和runat="server"属性,使您的脚本可被代码引用:

<script id="myScript" runat="server" type="text/javascript">

2-in代码隐藏,在page_load上,动态添加src属性:

this.myScript.Attributes.Add("src","http://example.com?Key=" + Key);

你完了!

代码隐藏:

public Key { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Key = "123456";
    }
}

标记:

 <script type="text/javascript" src="http://example.com?Key=<%= Key %>">
 </script>