zoukankan      html  css  js  c++  java
  • 【原创】Js调用后台方法

    对于开发前端的人员来说,为了一些特效,不让页面回发,可以需要异步去调用我们后台的方法,由于这个问题比较老了,牛人可以到别处看看了,哈哈。

    目前的技术也是比较多,实现方式也各个相同,只要按照每个技术规则就很好的实现了。废话不说,本节内容如下:

    (1)利用一般处理文件来实现调用后台方法

    (2)利用Jquery调用后台方法

    (3)利用微软自带的PageMethods

    (4)利用AjaxPro实现调用后台方法

    开始了。。。。,本节只讲怎么实现,至于理念和深入的资料不会在本节中细讲

    一:利用一般处理文件来实现调用后台方法

    这个其实要利用Jquery来实现,建立一个项目,在此项目上建立一个ashxToBack.aspx窗口用于做测试,前台代码如下:

     1 <html xmlns="http://www.w3.org/1999/xhtml" >
     2 <head runat="server">
     3     <title>无标题页</title>
     4     <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
     5     
     6     <script type="text/javascript">
     7         $(document).ready(function() {
     8             $("#btn_Sumbit").click(function() {
     9 
    10                 $.ajax({
    11                     type: "POST",
    12                     url: "ashxToBack.ashx",
    13                     dataType: "html",
    14                     data: "name=" + "ZhangSan",
    15                     beforeSend: function(XMLHttpRequest) {
    16                         //$("#showResult").text("正在查询");           
    17                     },
    18                     success: function(msg) {
    19                         alert("您好," + msg);
    20                     },
    21                     complete: function(XMLHttpRequest, textStatus) {
    22 
    23                     },
    24                     error: function() {
    25                         //错误处理
    26                     }
    27                 });
    28             });
    29         });
    30 
    31     </script>
    32 </head>
    33 <body>
    34     <form id="form1" runat="server">
    35     <div>
    36            <input id="btn_Sumbit" type="button" onclick="form_Submit()" value="测 试"/>
    37     </div>
    38     </form>
    39 </body>
    40 </html>

    再建立一个一般处理文件ashxToBack.ashx,代码如下:

     1  public void ProcessRequest(HttpContext context)
     2         {
     3             context.Response.ContentType = "text/plain";
     4 
     5             if (!string.IsNullOrEmpty(context.Request.Form["name"]))
     6             {
     7                 context.Response.Write(context.Request.Form["name"]);
     8                 context.Response.End();
     9             }
    10         }

    测试一下,是不是很简单,其实这个可以传自定类,并且以JSON方式传递,方便快捷,并且微软在3.5框架后对JSON已经有专门的类进行处理了,有兴趣的人可以去搜索相关资料,很多的,不多说,继续。

    二:利用Jquery调用后台方法

    建立一个页面JqueryToBack_Simply.aspx,代码如下:

     1 <html xmlns="http://www.w3.org/1999/xhtml" >
     2 <head runat="server">
     3     <title>利用Jquery调用后台方法</title>
     4      <script src="jquery-1.4.2.min-vsdoc.js" type="text/javascript"></script>
     5      <script type="text/javascript">
     6          //返回复合类型 
     7          $(document).ready(function() {
     8              $('#btn_Submit').click(function() {
     9                  $.ajax({
    10                      type: "POST",
    11                      contentType: "application/json",
    12                      url: "JqueryToBack_Simply.aspx/GetClass",
    13                      data: "{}",
    14                      dataType: 'json',
    15                      success: function(result) {
    16                          $(result.d).each(function() {
    17                               alert("用户ID:" + this['UserID'] + " ,用户名:" + this['UserName']);
    18                              
    19                          });
    20 
    21 
    22                      }
    23                  });
    24              });
    25          });
    26      </script>
    27 </head>
    28 <body>
    29     <form id="form1" runat="server">
    30     <div>
    31         <input type="button" id="btn_Submit" value=" 返回复合类型"/>  
    32     </div>
    33     </form>
    34 </body>
    35 </html>

    后台代码如下:

     1  protected void Page_Load(object sender, EventArgs e)
     2         {
     3 
     4         }
     5 
     6         /// <summary>
     7         /// 返回一个复合类型
     8         /// </summary>
     9         /// <returns></returns>
    10         [WebMethod]
    11         public static UserInfo GetClass()
    12         {
    13             return new UserInfo { UserID = "100000", UserName = "杨新华" };
    14         }
    15         public class UserInfo
    16         {
    17             public string UserID { get; set; }
    18             public string UserName { get; set; }
    19         }

    三:利用微软自带的PageMethods

    这个得依赖于ScriptManager组件,代码如下:

     1 <html xmlns="http://www.w3.org/1999/xhtml" >
     2 <head runat="server">
     3     <title>PageMethods调用后台代码</title>
     4 
     5     <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
     6     
     7     <script type="text/javascript">
     8         function form_Submit() {
     9            
    10             PageMethods.doSubmit("测试", function(jsonObj) {
    11                 alert(jsonObj);
    12             });
    13            
    14         }
    15     </script>
    16 </head>
    17 <body>
    18     <form id="form1" runat="server">
    19         <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    20         </asp:ScriptManager>
    21 
    22     
    23     <div>
    24         <input type="button" id="btn_Submit" value="提 交" onclick="form_Submit()" />
    25     </div>
    26     </form>
    27 </body>
    28 </html>

    后台代码如下:

     1  protected void Page_Load(object sender, EventArgs e)
     2         {
     3 
     4         }
     5 
     6             /// <summary>
     7     /// 登入
     8     /// </summary>
     9     /// <param name="account"></param>
    10     /// <param name="password"></param>
    11     /// <param name="isRememberMe"></param>
    12     /// <returns></returns>
    13         [WebMethod]
    14         public static string doSubmit(string msg)
    15         {
    16             return msg;
    17         }

    注意几项:

    第一:ScriptManager 必须设置成  EnablePageMethods="true"

    第二:后台方法必须是静态的。

    第三:后台方法上面必须添加特性标记 [System.Web.Services.WebMethod]

    四:利用AjaxPro实现调用后台方法

    这个需要下载AjaxPro.dll或是AjaxPro.2.dll,我这里用的是AjaxPro.2.dll

    首先在你项目中引用这个AjaxPro.2.dll,接下来在Web.Config中配置它

      <httpHandlers>

          <add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2 "/>
        </httpHandlers>

    这样就可以使用了,

    新建页面AjaxPro_Test.aspx,前台代码如下:

     1 <html xmlns="http://www.w3.org/1999/xhtml" >
     2 <head runat="server">
     3     <title>AjaxPro来实现调用后台</title>
     4 
     5     <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
     6     <script type="text/javascript">
     7         function form_Submit() {
     8             JqueryBackMethod.AjaxPro_Test.GetMessage("AjaxPro", function(obj) {
     9               alert(obj.value);
    10             });
    11         }       
    12     </script>
    13 </head>
    14 <body>
    15     <form id="form1" runat="server">
    16     <div>
    17         <input id="btn_Sumbit" type="button" onclick="form_Submit()" value="测 试"/>
    18     </div>
    19     </form>
    20 </body>
    21 </html>

    后台代码如下:

     protected void Page_Load(object sender, EventArgs e)
            {
                Utility.RegisterTypeForAjax(typeof(JqueryBackMethod.AjaxPro_Test));
            }
    
            [AjaxMethod]
            public string GetMessage(string testText)
            {
                return "Hello " + testText;
            }

    注意事项:

    第一:Utility.RegisterTypeForAjax(typeof(JqueryBackMethod.AjaxPro_Test)); 是相当于注册哪个类可以被前台js调用,如果这个类有命名空间,则在注册时必须加上命名空间

    前台调用也是如此

    第二:在后台方法上必须添加特性:  [AjaxMethod]

    第三:当你在项目中使用第二种方法时,再用本方法就不行了,原因是这个方法在Web.config中注册时已经加了一些额外的处理器,导致不能运行。这个额外处理器可以在运行这个页面时查看源代码即可。源代码如下:

    1 <script type="text/javascript" src="/ajaxpro/prototype.ashx"></script>
    2 <script type="text/javascript" src="/ajaxpro/core.ashx"></script>
    3 <script type="text/javascript" src="/ajaxpro/converter.ashx"></script>
    4 <script type="text/javascript" src="/ajaxpro/JqueryBackMethod.AjaxPro_Test,JqueryBackMethod.ashx"></script>

      

     好了,本节就说到这,只是给大家开个山,更多技术知识请在网络上查询相关资料了解。

     欢迎转载,转载请标注原创地址:http://www.cnblogs.com/yxhblog/archive/2012/07/26/2610264.html

  • 相关阅读:
    测试开发系列之Python开发mock接口(三)
    测试开发系列之Python开发mock接口(二)
    测试开发系列之Python开发mock接口(一)
    python单元测试unittest
    Linux–Nginx攻略
    cookies和session
    Selenium-------ActionChainApi接口详解
    Selenium-----wait的三种等待
    Selenium-Switch与SelectApi接口
    app token session rsp
  • 原文地址:https://www.cnblogs.com/yxhblog/p/2610264.html
Copyright © 2011-2022 走看看