好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

学习.net与ajax的详细案例总结

学习.net与ajax的详细案例总结

学习.net与ajax的详细案例总结

昨天看了一天的ajax,今天又看了两个小时,终于弄出来个门道,其实ajax不是难,不是枯燥,而是自己不会用,这是根本所在

下面分享学习经验,一下是我程序的下载地址: http://vdisk.weibo.com/s/BQ2aD  或者这个地址  http://download.csdn.net/detail/heikeyuit/5398845

首先了解什么是ajax。

AJAX不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的 Web 应用程序的技术。

通过 AJAX,您的 JavaScript 可使用JavaScript的XMLHttpRequest对象来直接与服务器进行通信。通过这个对象,您的 JavaScript 可在不重载页面的情况与Web服务器交换数据。

AJAX 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求),这样就可使网页从服务器请求少量的信息,而不是整个页面。

 

一提到javascript,大家都会想到浏览器的兼容性问题,其实ajax也需要考虑到这个问题。因为不同浏览器使用的web的javascript的类不一样,所以产生的效果也不会一样的。下面不瞎说了,直接引入代码供大家参考。

        {
              var   xmlhttp;  //  非IE浏览器创建XmlHttpRequest对象 
             if  (window.XMLHttpRequest){
                xmlhttp  =  new   XMLHttpRequest();
            }
              //  IE浏览器创建XmlHttpRequest对象 
             if   (window.ActiveXObject) {
                  try   {
                    xmlhttp  =  new  ActiveXObject("Microsoft.XMLHTTP" );
                }
                  catch   (e) {
                      try   {
                        xmlhttp  =  new  ActiveXObject("msxml2.XMLHTTP" );
                    }
                      catch   (ex) { }
                }
            }
              if  (! xmlhttp) {
                alert( "创建xmlhttp对象异常" );
                  return   false  ;
            }
             //   xmlhttp.open("POST", "GetDate.ashx?nd=" + new Date(), false); //向服务器某个页面发出请求 
            xmlhttp.open("GET", "URL“,  false  ); 
            
            xmlhttp.onreadystatechange  =  function   () {
                  if  (xmlhttp.readyState == 4 ) {
                      if  (xmlhttp.status == 200) { //  如果是状态码则显示成功 
                         //  document.getElementById("Text1").value = xmlhttp.responseText; 
                        xxxxx =  xmlhttp.responseText;// 在此处我们可以将我们传递的参数返回给我们的html标签,或者其他变量处理问题 
                    }   //  responseText为服务器返回的文本 
                     else   {
                        alert( "AJAX服务器返回错误" );
                    }
                }
            }
            xmlhttp.send();  //  开始发送请求 
        }

这只是前台的代码,就这些代码就已经足够了,实现了局部刷新页面的功能,剩下的后台代码是根据项目的不同而定,我在这里不必引入了。

大家看到这些代码感觉怎么样,对于刚学习javascript或者ajax的同学,要想记住这些代码,真的是很难啊,还有怎么去理解这些东西呢,我上面基本都有注释,大家一般可以理解。但是如果每个页面都需要局部刷新的话,这样就会感觉每个页面都要写这样的代码是不是很麻烦啊,jQuery帮助我们完成了很多东西,这样可以减轻我们开发项目的难度,以下是使用jQuery的代码:

 $.ajax({
   type:  "POST" ,
   url:  "some.php" ,
   data:  "name=John&location=Boston" ,
   success:   function  (msg){
     alert(  "Data Saved: " +  msg );
   }
}); 

另一种方式

$.post("test.php", { name: "John", time: "2pm"  },
     function  (data){
     alert( "Data Loaded: " +  data);
   }); 

是不是很简单啊,在这里我们这是调用他写好的函数,我们就可以实现我们的无刷新代码了,现在感觉是不是无刷新页面是不是很简单了,但是我们这只是传递个小数据而已,如果从数据库中提取数据时就会很麻烦的,以下引入我的部分代码,让大家思考一下

以下是我实现无刷新评论并显示的前台和后台代码:

 <%  @ Page Language  =  "  C#  "   AutoEventWireup  =  "  true  "   CodeBehind  =  "  AjaxComment.aspx.cs  "   Inherits  =  "  ajax学习.无刷新评论.AjaxComment1  "   %> 

 <!  DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"  > 

 <  html   xmlns  ="http://www.w3.org/1999/xhtml"  > 
 <  head   runat  ="server"  > 
     <  title  ></  title  > 
     <  script   src  ="js/jquery-1.9.1.js"   type  ="text/javascript"  ></  script  > 
     <  script   type  ="text/javascript"  >  
        $(  function   () {
            $(  "  #btnComment  "  ).click(  function   () {
                  var   comment   =   $(  "  #txtComment  "  ).val();
                
                $.post(  "  AjaxComment.ashx  "  ,{  "  msg  "  :comment},
                  function   (data, status) {
                      if   (status   !=   "  success  "  ) {
                        alert(  "  发表评论失败,请重试  "  );
                          return  ;
                    }
                      if   (data   ==   "  ok  "  ) {
                          var   newComment   =   $(  "  <li>评论日期:  "  +  new   Date().toString()  +  "  ,IP:,  "  +  "  本机  "  +  "  内容:  "  +  comment  +  "  </li>  "  );
                        $(  "  #ulComment  "  ).append(newComment);
                        alert(  "  评论发表成功  "  );
                    }
                      else   {
                        alert(  "  评论发表有问题  "  );
                    }
                });
            });
        });
      </  script  > 
 </  head  > 
 <  body  > 
     <  form   id  ="form1"   runat  ="server"  > 
     <  div  > 
         <  asp:ObjectDataSource   ID  ="ObjectDataSource1"   runat  ="server"   
            DeleteMethod  ="Delete"   InsertMethod  ="Insert"   
            OldValuesParameterFormatString  ="original_{0}"   SelectMethod  ="GetData"   
            TypeName  ="ajax学习.DataSetCommentTableAdapters.T_CommentTableAdapter"   
            UpdateMethod  ="Update"  > 
             <  DeleteParameters  > 
                 <  asp:Parameter   Name  ="Original_Id"   Type  ="Int64"   /> 
             </  DeleteParameters  > 
             <  InsertParameters  > 
                 <  asp:Parameter   Name  ="IP"   Type  ="String"   /> 
                 <  asp:Parameter   Name  ="Msg"   Type  ="String"   /> 
                 <  asp:Parameter   Name  ="PostDate"   Type  ="String"   /> 
             </  InsertParameters  > 
             <  UpdateParameters  > 
                 <  asp:Parameter   Name  ="IP"   Type  ="String"   /> 
                 <  asp:Parameter   Name  ="Msg"   Type  ="String"   /> 
                 <  asp:Parameter   Name  ="PostDate"   Type  ="String"   /> 
                 <  asp:Parameter   Name  ="Original_Id"   Type  ="Int64"   /> 
             </  UpdateParameters  > 
         </  asp:ObjectDataSource  > 
         <  ul   id  ="ulComment"  > 
         <  asp:Repeater   ID  ="Repeater1"   runat  ="server"   DataSourceID  ="ObjectDataSource1"  > 
             <  ItemTemplate  > 
                 <  li  > 评论日期: <%  #  Eval  (  "  PostDate  "  )  %> ,IP: <%  #  Eval  (  "  IP  "  )  %> ,内容: <%  #  Eval  (  "  Msg  "  )  %>  <  br  /></  li  > 
             </  ItemTemplate  > 
         </  asp:Repeater  > 
         </  ul  > 
     <  textarea   id  ="txtComment"   cols  ="20"   rows  ="10"  ></  textarea  ><  br  /> 
     <  input   id  ="btnComment"   type  ="button"  
        value  ="提交"   /> 
     </  div  > 
     </  form  > 
 </  body  > 
 </  html  > 

后台代码(AjaxComment.ashx)

 using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Web;
  using   ajax学习.DataSetCommentTableAdapters;
  using   System.Web.Services;
  namespace   ajax学习.无刷新评论
{
      ///   <summary> 
     ///   AjaxComment 的摘要说明
      ///   </summary> 
    [WebService(Namespace =  "  http://tempuri.org/  "  )]
    [WebServiceBinding(ConformsTo  =  WsiProfiles.BasicProfile1_1)]
      public   class   AjaxComment : IHttpHandler
    {

          public   void   ProcessRequest(HttpContext context)
        {
            context.Response.ContentType  =  "  text/plain  "  ;
              string  msg = context.Request[ "  msg  "  ];
              new   T_CommentTableAdapter().Insert(context.Request.UserHostAddress,msg,DateTime.Now.ToString());// 使用的是强类型DataSet 
            context.Response.Write(  "  ok  "  );
        }

          public   bool   IsReusable
        {
              get  
            {
                  return   false  ;
            }
        }
    }
} 

大家看完前台代码是不是有疑问了,如果传递很多字段,很多属性的数据时,该怎么办呢,如果每个数据都是这样的自己split()一下的话,那么做大项目的话肯定会累屎了,下面jQuery有帮我们做了件好事情,就是json的使用,下面我引入我的使用无刷新评论的json代码

前台代码:

 <!  DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"  > 
 <  html   xmlns  ="http://www.w3.org/1999/xhtml"  > 
 <  head  > 
     <  title  ></  title  > 
     <  script   src  ="js/jquery-1.9.1.js"   type  ="text/javascript"  ></  script  > 
     <  script   type  ="text/javascript"  >  
        $(  function   () {
            $.post(  "  PagedServices.ashx  "  , {   "  action  "  :   "  getpagecount  "   },   function   (data, status) {
                  for   (  var   i   =   1  ; i   <=  data; i  ++  ) {
                      var   td   =   $(  "  <td><a href=''>  "   +   i   +   "  </a></td>  "  );
                    $(  "  #trPage  "  ).append(td);
                }
                $(  "  #trPage td  "  ).click(  function   (e) {
                    e.preventDefault();  //  不要导向链接地址 
                     $.post(  "  PagedServices.ashx  "  , {   "  action  "  :   "  getpagedata  "  ,   "  pagenum  "  : $(  this  ).text()},
                      function   (data, status) {
                          var   comments   =   $.parseJSON(data);
                        $(  "  #ulComments li  "  ).remove();
                          for   (  var   i   =   0  ; i   <   comments.length; i  ++  ) {
                              var   comment   =   comments[i];
                              var   li   =   $(  "  <li>  "   +   comment.Id   +   "  ---  "   +   comment.IP   +   "  ---  "   +   comment.Msg   +   "  ---  "   +   comment.PostDate   +   "  </li>  "  );
                            $(  "  #ulComments  "  ).append(li);
                        }
                    });
                });
            });
        });
      </  script  > 
 </  head  > 
 <  body  > 
     <  ul   id  ="ulComments"  ></  ul  > 
     <  table  ><  tr   id  ="trPage"  ></  tr  ></  table  > 
 </  body  > 
 </  html  > 

后台代码:

 using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Web;
  using   System.Web.Services;
  using   ajax学习.DataSetCommentTableAdapters;
  using   System.Web.Script.Serialization;
  namespace   ajax学习.无刷新分页
{
      ///   <summary> 
     ///   PagedServices 的摘要说明
      ///   </summary> 
    [WebService(Namespace =  "  http://tempuri.org/  "  )]
    [WebServiceBinding(ConformsTo  =  WsiProfiles.BasicProfile1_1)]
      public   class   PagedServices : IHttpHandler
    {

          public   void   ProcessRequest(HttpContext context)
        {
            context.Response.ContentType  =  "  text/plain  "  ;
               //   context.Response.Write("Hello World"); 
             string  action=context.Request[ "  action  "  ];
              var  adapter =  new   T_CommentTableAdapter();
              if  (action ==  "  getpagecount  "  )
            {
                
                  int  count= adapter.SelectCount().Value;
                  int  pagecount=count/ 10  ;
                  if (count% 10 != 0  )
                {
                    pagecount ++ ;
                }
                context.Response.Write(pagecount);
            }
              else   if (action== "  getpagedata  "  )
            {
                  string  pagenum=context.Request[ "  pagenum  "  ];
                  int  iPageNum =  Convert.ToInt32(pagenum);
                  var  data = adapter.GetPagedData((iPageNum -  1 ) *  10  +  1 , iPageNum *  10  );
                List <Comments> list= new  List<Comments>  ();
                  foreach ( var  row  in   data)
                {
                    list.Add(  new  Comments() { Id = ( int )row.Id, IP = row.IP, Msg = row.Msg, PostDate =  row.PostDate, });
                }
                JavaScriptSerializer jss  =  new   JavaScriptSerializer();
                context.Response.Write(jss.Serialize(list));
            }  
        }

          public   bool   IsReusable
        {
              get  
            {
                  return   false  ;
            }
        }
    }

      public   class   Comments
    {
          public   int  Id {  get ;  set  ; }
          public   string  IP{ get ; set  ;}
          public   string  Msg{ get ; set  ;}
          public   string  PostDate{ get ; set  ;}
    }
} 

这样我们真的是省了很多力气啊,是不是jQuery很强大啊。。。。。。。。。。。。。

然后吧,微软感觉我必须封装自己的ajax,这样使得开发者做项目变得容易一些,微软真的是帮我们封装好了一个,但是对于高手来说,大家都不想用,感觉这样的代码太呆板,一点不灵活,我再下面引入代码,供新手参考:(不了解ajax运行原理的新手一样可以使用ajax快速开发新的项目)

 <%  @ Page Language  =  "  C#  "   AutoEventWireup  =  "  true  "   CodeBehind  =  "  UpdatPanel.aspx.cs  "   Inherits  =  "  ajax学习.UpdatePanel.UpdatPanel  "   %> 

 <%  @ Register assembly  =  "  AjaxControlToolkit  "   namespace  =  "  AjaxControlToolkit  "   tagprefix  =  "  cc1  "   %> 

 <!  DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"  > 

 <  html   xmlns  ="http://www.w3.org/1999/xhtml"  > 
 <  head   runat  ="server"  > 
     <  title  ></  title  > 
 </  head  > 
 <  body  > 
     <  form   id  ="form1"   runat  ="server"  > 
     <  asp:ScriptManager   ID  ="ScriptManager1"   runat  ="server"  > 
     </  asp:ScriptManager  > 
     <  div  > 
         <  asp:TextBox   ID  ="TextBox1"   runat  ="server"  ></  asp:TextBox  > 
         <  asp:Button   ID  ="Button1"   runat  ="server"   Text  ="普通刷新页面显示当前时间"   
            onclick  ="Button1_Click"   /> 
     </  div  > 
     <  div  >    
         <  asp:UpdatePanel   ID  ="UpdatePanel1"   runat  ="server"  > 
             <  ContentTemplate  > 
                 <  asp:TextBox   ID  ="TextBox2"   runat  ="server"  ></  asp:TextBox  >  <  asp:Button   ID  ="Button2"   runat  ="server"   onclick  ="Button2_Click"   
                    Text  ="Ajax无刷新显示当前时间"   /> 
                 <  br   /> 
             </  ContentTemplate  > 
         </  asp:UpdatePanel  > 
     </  div  > 
     </  form  > 
 </  body  > 
 </  html  > 

但是微软后来真的是开发一个很好地工具,那就是ajax与WCF的结合,废话少说,引入代码,供大家思考

 <%  @ Page Language  =  "  C#  "   AutoEventWireup  =  "  true  "   CodeBehind  =  "  WCF_Ajax.aspx.cs  "   Inherits  =  "  ajax学习.WCF之Ajax.WCF_Ajax  "   %> 

 <!  DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"  > 

 <  html   xmlns  ="http://www.w3.org/1999/xhtml"  > 
 <  head   runat  ="server"  > 
     <  title  ></  title  > 
    
     <  script   language  ="javascript"   type  ="text/javascript"  > 
 //   <![CDATA[ 

         function   Button1_onclick() {
            PersonService.GetPerson(  1  ,   function   (data) {
                alert(data.Name);
            },
              function   () {
                alert(  "  失败  "  );
            });
        }

  //   ]]> 
     </  script  > 
 </  head  > 
 <  body  > 
     <  form   id  ="form1"   runat  ="server"  > 
     <  div  > 
    
         <  asp:ScriptManager   ID  ="ScriptManager1"   runat  ="server"  > 
             <  Services  > 
                 <  asp:ServiceReference   Path  ="./PersonService.svc"   />  //注意路径处理问题,  
             </  Services  > 
         </  asp:ScriptManager  > 
         <  input   id  ="Text1"   type  ="text"   /> 
         <  input   id  ="Button1"   type  ="button"   value  ="button"   onclick  ="return Button1_onclick()"   /> 
         <  br   /> 
    
     </  div  > 
     </  form  > 
 </  body  > 
 </  html  > 

后台代码:(PersonService.svc)

 using   System;
  using   System.Collections.Generic;
  using   System.Linq;
  using   System.Runtime.Serialization;
  using   System.ServiceModel;
  using   System.ServiceModel.Activation;
  using   System.ServiceModel.Web;
  using   System.Text;

  namespace   ajax学习.WCF之Ajax
{
    [ServiceContract(Namespace  =  ""  )]
    [AspNetCompatibilityRequirements(RequirementsMode  =  AspNetCompatibilityRequirementsMode.Allowed)]
      public   class   PersonService
    {
          //   要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
          //   要创建返回 XML 的操作,
          //       请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
          //       并在操作正文中包括以下行:
          //           WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; 
         [OperationContract]
          public   void   DoWork()
        {
              //   在此处添加操作实现 
             return  ;
        }

        [OperationContract]
          public  Person GetPerson( int   id)
        {
              return   new  Person(){Name= "  Tom  " ,Age= 30  };
        }

          //   在此处添加更多操作并使用 [OperationContract] 标记它们 
     }

      public   class   Person
    {
          public   string  Name {  get ;  set  ; }
          public   int  Age{ get ; set  ;}

    }
} 

使用了WCF后我们就可以在javascript中直接调用后台封装的属性和方法了,就这样,很简单吧,言归正传,学会才是硬道理,我将我的代码程序上传到网上了,大家如果不懂的话,可以自己调试一下。以下是下载地址: http://vdisk.weibo.com/s/BQ2aD  或者这个地址  http://download.csdn.net/detail/heikeyuit/5398845

 

朦胧中,遇见了你,因为你的存在,我的生活得以改变;在改变中,我们彼此快乐;在相处中,我们彼此分享。因为你的分享,我才能够不断进步,在这里真心的说一声谢谢。

 

分类:  .net分享

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于学习.net与ajax的详细案例总结的详细内容...

  阅读:37次