Timer中的客户端脚本不工作
本文关键字:工作 脚本 客户端 Timer | 更新日期: 2023-09-27 18:22:05
我只是想学习一些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时,需要使用ScriptManager而不是ClientScript。
将您的代码更改为:
ScriptManager.RegisterStartupScript(this,this.GetType(), someScript, @"alert('I was called from Content page!');", true);
您忘记了一个;
ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!');", true);
大多数浏览器都有某种类型的错误控制台,您可以在这些问题发生时看到它们。