asp.net ajax动态显示时间
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>ajax动态显示时间 </title>
- <script language="javascript" type="text/javascript">
- function btnInvoke_onclick()
- {
- var txtName=$get("txtName").value;
- //var txtName=document.getElementById("txtName").value;
- PageMethods.SayHello(txtName,SayHelloShow);
- }
- //回调函数
- function SayHelloShow(res)
- {
- $get("result").innerHTML=res;
- //document.getElementById("result").innerHTML=res;
- }
- function TimeCall()
- {
- setInterval("btnInvoke_onclick()",1000);
- //setTimeout("btnInvoke_onclick()",1000);
- }
- </script>
- </head>
- <body onload="TimeCall()">
- <form method="get" runat="server">
- <asp:ScriptManager runat="server" EnablePageMethods="true" />
- <input type="text" value="动态时间 " />
- <input type="button" value="测试" onclick="return btnInvoke_onclick()" />
- <div ></div>
- <br />
- <textarea rows="10" cols="50" />
- </form>
- </body>
- </html>
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Web.Services;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- [WebMethod]
- public static string SayHello(string name)
- {
- return string.Format("你好{0}!现在时间:{1}", name, DateTime.Now.ToString());
- }
- }
- 注意:
- 1 <asp:ScriptManager runat="server" EnablePageMethods="true" />中的EnablePageMethods
- 要为true,表示客户端页面能直接调用服务器端页面的静态方法.
- 2
- [WebMethod]
- public static string SayHello(string name)
- {
- return string.Format("你好{0}!现在时间:{1}", name, DateTime.Now.ToString());
- }
- 必须是静态方法.必须加[WebMethod]
- 3 PageMethods.SayHello(txtName,SayHelloShow);
- 表示服务器页面方法中的SayHello,SayHelloShow表示回调函数,主要用于前台显示