asp.net ajax动态显示时间

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>ajax动态显示时间 </title>
  6. <script language="javascript" type="text/javascript">
  7. function btnInvoke_onclick()
  8. {
  9. var txtName=$get("txtName").value;
  10. //var txtName=document.getElementById("txtName").value;
  11. PageMethods.SayHello(txtName,SayHelloShow);
  12. }
  13. //回调函数
  14. function SayHelloShow(res)
  15. {
  16. $get("result").innerHTML=res;
  17. //document.getElementById("result").innerHTML=res;
  18. }
  19. function TimeCall()
  20. {
  21. setInterval("btnInvoke_onclick()",1000);
  22. //setTimeout("btnInvoke_onclick()",1000);
  23. }
  24. </script>
  25. </head>
  26. <body onload="TimeCall()">
  27. <form method="get" runat="server">
  28. <asp:ScriptManager runat="server" EnablePageMethods="true" />
  29. <input type="text" value="动态时间 " />
  30. <input type="button" value="测试" onclick="return btnInvoke_onclick()" />
  31. <div ></div>
  32. <br />
  33. <textarea rows="10" cols="50" />
  34. </form>
  35. </body>
  36. </html>
  37. using System;
  38. using System.Data;
  39. using System.Configuration;
  40. using System.Web;
  41. using System.Web.Security;
  42. using System.Web.UI;
  43. using System.Web.UI.WebControls;
  44. using System.Web.UI.WebControls.WebParts;
  45. using System.Web.UI.HtmlControls;
  46. using System.Web.Services;
  47. public partial class _Default : System.Web.UI.Page
  48. {
  49. protected void Page_Load(object sender, EventArgs e)
  50. {
  51. }
  52. [WebMethod]
  53. public static string SayHello(string name)
  54. {
  55. return string.Format("你好{0}!现在时间:{1}", name, DateTime.Now.ToString());
  56. }
  57. }
  58. 注意:
  59. 1 <asp:ScriptManager runat="server" EnablePageMethods="true" />中的EnablePageMethods
  60. 要为true,表示客户端页面能直接调用服务器端页面的静态方法.
  61. 2
  62. [WebMethod]
  63. public static string SayHello(string name)
  64. {
  65. return string.Format("你好{0}!现在时间:{1}", name, DateTime.Now.ToString());
  66. }
  67. 必须是静态方法.必须加[WebMethod]
  68. 3 PageMethods.SayHello(txtName,SayHelloShow);
  69. 表示服务器页面方法中的SayHello,SayHelloShow表示回调函数,主要用于前台显示