【问题标题】:Client script in Timer is not working计时器中的客户端脚本不起作用
【发布时间】:2013-07-11 20:18:44
【问题描述】:

我只是想学习一些 Asp.net Ajax 的东西并从我的 C# 脚本中调用 javascript。

我有一个计时器,它触发一个调用超级简单的 javascript 警报函数的方法。 它还每 10 秒更新一次时间。现在看起来我的代码应该可以工作了。没有构建错误,没有例外,只是它不起作用。更新时间的 C# 部分。 javascript 不会发出警报。

    <%@ Page Language="C#" %>

    <!DOCTYPE html>
    <html>

    <head runat="server">
        <title></title>
        <script runat="server">
        protected void Page_load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Label1.Text = DateTime.Now.ToString();
            }
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            const string someScript = "alertMe";
            Label1.Text = DateTime.Now.ToString();
            ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!')", true);
        }
    </script>

    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager runat="server"> </asp:ScriptManager>
     <asp:UpdatePanel runat="server">
         <ContentTemplate>
             <asp:Label runat="server" ID="Label1"></asp:Label>
             <asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick ="Timer1_Tick"></asp:Timer>
         </ContentTemplate>
     </asp:UpdatePanel>
        </div>
        </form>
    </body>
    </html>

【问题讨论】:

  • 这一切都很糟糕,但 UpdatePanel 需要注意任何触发器,因此请尝试为 Timer 添加一个。
  • 嗯,更新标签的 C# 部分工作正常,并执行异步回发,每 10 秒更改标签中的时间。我对 UpdatePanel 没有任何问题,我的问题是为什么 javascript 不能正常工作。

标签: c# javascript asp.net asp.net-ajax


【解决方案1】:

当您将触发回发的元素放入 UpdatePanel 时,您需要使用 ScriptManager 而不是 ClientScript。

将您的代码更改为:

ScriptManager.RegisterStartupScript(this,this.GetType(), someScript, @"alert('I was called from Content page!');", true);

【讨论】:

  • 非常感谢你的作品。一个小问题。如果我的页面中已经包含一个 javascript 库(比如说 jQuery),我可以在传入的脚本中使用 jquery 命令吗?
  • 是的,当然,它也适用于 jQuery 或任何其他 Javascript 库。
【解决方案2】:

你忘记了一个;

ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!');", true);

大多数浏览器都有某种类型的错误控制台,您可以在这些问题发生时看到它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    相关资源
    最近更新 更多