KimhillZhang  

很多东西都不会,从头学起;这里贴使用PageMethods调用后台方法

在后台上写两个方法,一个是有参,一个无参

 

      [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static object GetStatus()
        {
            return System.DateTime.Now.ToString();
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static object SetName(string firstName, string lastName)
        {
            return firstName + " " + lastName;
        }

 

在脚本上进行调用

 

<script language="javascript" type="text/javascript">
       /*
     注意事项: 

    (a)需要调用的服务器端方法必须以System.Web.Services.WebMethod特性进行标记
     (b)需要调用的服务器端方法必须为公共静态方法
     (c)需要调用的服务器端方法应写在.aspx页面(或对应的后台代码文件)中,不应写在用户控件中
       */

       window.setInterval(function () {
           PageMethods.GetStatus(function (result) {
               if (result) {
                   alert(result);//弹出当前时间
               }
           });
       }, 3000);

       window.onload = function () {
           PageMethods.SetName("zhang", "jinshan", function (result) {
               alert(result);//弹出姓名
           });
       }

       //以下的写法是错误的:直接
         PageMethods.SetName("zhang", "jinshan", function (result) {
               alert(result);//弹出姓名

           });
    </script>

在表单中需要添加 EnablePageMethods="true"

 

 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    
posted on 2012-06-27 17:44  KimhillZhang  阅读(1260)  评论(0编辑  收藏  举报