昨天看了一天的ajax,今天又看了兩個小時,終於弄出來個門道,其實ajax不是難,不是枯燥,而是自己不會用,這是根本所在
下面分享學習經驗,以下是我程序代碼的下載地址:http://vdisk.weibo.com/s/BQ2aD 或者這個地址 http://download.csdn.net/detail/heikeyuit/5398845
首先了解什么是ajax。
{ 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