之前在認(rèn)識Ajax初步理解中介紹了對Ajax的初步理解,本文將介紹在ASP.NET中如何方便使用Ajax,第一種當(dāng)然是使用jQuery的ajax,功能強大而且操作簡單方便,第二種是使用.NET封裝好的ScriptManager。
相關(guān)免費學(xué)習(xí)推薦:ajax(視頻)
$.ajax向普通頁面發(fā)送get請求
這是最簡單的一種方式了,先簡單了解jQuery ajax的語法,最常用的調(diào)用方式是這樣:$.ajax({settings}); 有幾個常用的setting,全部參數(shù)及其解釋可以去jQuery官方API文檔查詢
1. type:請求方式 get/post
2. url:請求的Uri
3. async:請求是否為異步
4. headers:自定義的header參數(shù)
5. data:發(fā)往服務(wù)器的參數(shù)
6. dataType:參數(shù)格式,常見的有string、json、xml等
7. contents:決定怎樣解析response的一個”字符串/正則表達式” map
8. contentType:發(fā)送到服務(wù)器的額數(shù)據(jù)的內(nèi)容編碼類型,它的默認(rèn)值是"application/x-www-form-urlencoded; charset=UTF-8""。
9. success:請求成功后調(diào)用的句柄
10.error:請求失敗后調(diào)用的句柄
沒使用過jQuery的ajax話這樣看有些云里霧里的感覺,來看一個簡單例子
首先使用Visual Studio新建一個WebApplication,把jQuery.js引入project,然后添加兩個頁面,Default.aspx作為測試用
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.Default" %> <!DOCTYPE html > <html> <head runat="server"> <title>Ajax</title> <script src="jQuery.js" type="text/javascript"></script> <style type="text/css"> html, body, form { width: 100%; height: 100%; padding: 0px; margin: 0px; } #container { margin: 100px; height: 300px; width: 500px; background-color: #eee; border: dached 1px #0e0; } </style> </head> <body> <form id="form1" runat="server"> <p id="container"> <input type="button" value="Test Ajax" onclick="testGet()" /> <br /> </p> <script type="text/javascript"> function setContainer(text) { document.getElementById("container").innerHTML += ('<br/>' + text); } function testGet() { $.ajax({ type: 'get', url: 'NormalPage.aspx', async: true, success: function (result) { alert(result); }, error: function () { setContainer('ERROR!'); } }); } </script> </form> </body> </html>
NormalPage.aspx作為請求頁面,先不做任何處理。在Default.aspx頁面中的JavaScript中可以看到testGet函數(shù)就利用jQuery的ajax向Normal.aspx發(fā)送了了一個get請求,沒寫的參數(shù)使用jQuery默認(rèn)參數(shù),這個調(diào)用沒使用任何參數(shù),簡單向Normal.aspx頁面發(fā)送請求,請求成功則alert全部response(即success方法參數(shù):result,jQuery會把responseText傳入success方法第一個參數(shù)),請求失敗則向p中添加一行錯誤提示文本。如果一切正常,可以看到頁面彈出對話框,對話框內(nèi)內(nèi)容即是Normal.aspx頁面內(nèi)容
一個簡單的get請求完成了,這樣的結(jié)果一般沒有多大用處,也不是ajax意圖所在,使用Ajax主要是想使用JavaScript可以異步向服務(wù)器發(fā)送特定請求,獲取服務(wù)器相關(guān)數(shù)據(jù),比如向服務(wù)器詢問天氣,然后獲得天氣數(shù)據(jù),更新頁面,而不是獲取整個頁面,換句話說,使用Ajax本身就是為了擺脫更新整個頁面來更新頁面數(shù)據(jù)這種模式,僅僅需要服務(wù)器給我們數(shù)據(jù)即可,這就需要調(diào)用服務(wù)器端的特定方法。
$.ajax GET請求調(diào)用服務(wù)器特定方法
我們這時候需要修改NormalPage.aspx,為其添加幾個方法供Default.aspx測試調(diào)用
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Web { public partial class NormalPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = Request.QueryString["action"]; Response.Clear(); //清除所有之前生成的Response內(nèi)容 if (!string.IsNullOrEmpty(action)) { switch (action) { case "getTime": Response.Write(GetTime()); break; case "getDate": Response.Write(GetDate()); break; } } Response.End(); //停止Response后續(xù)寫入動作,保證Response內(nèi)只有我們寫入內(nèi)容 } private string GetDate() { return DateTime.Now.ToShortDateString(); } private string GetTime() { return DateTime.Now.ToShortTimeString(); } } }
然后為Default.aspx添加一個新的方法,并修改button的onclick方法為新寫的函數(shù)
function testGet2() { $.ajax({ type: 'get', url: 'NormalPage.aspx', async: true, data:{action:'getTime'}, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
testGet2函數(shù)是在testGet函數(shù)的基礎(chǔ)上做了些許修改,首先對success方法做了更改,把得到的response寫到頁面;然后對請求添加了data參數(shù),請求向服務(wù)器發(fā)送了一個action:getTime的鍵值對,在get請求中jQuery會把此參數(shù)轉(zhuǎn)為url的參數(shù),上面寫法和這種寫法效果一樣
function testGet3() { $.ajax({ type: 'get', url: 'NormalPage.aspx?action=getTime', async: true, success: function (result) { setContainer(result); }, error: function () { setContainer('ERROR!'); } }); }
看一下執(zhí)行效果,這是Chrome的監(jiān)視結(jié)果
如果調(diào)試我們發(fā)現(xiàn)這個請求調(diào)用的服務(wù)器頁面NormalPage.aspx的GETime方法,并且response中只包含對有用的數(shù)據(jù),如果把請求中參數(shù)的值改為getDate,那么就會調(diào)用對應(yīng)GetDate方法。
$.ajax POST與json
這樣向一個頁面發(fā)送請求然后在Load事件處理程序中根據(jù)參數(shù)調(diào)用不同方法,清除Response,寫入Response,終止Response,而且傳入的參數(shù)局限性太大,好業(yè)余的趕腳,看看專業(yè)些解決方法。為project添加一個General Handler類型文件,關(guān)于HttpHandler相關(guān)內(nèi)容本文不做詳細解釋,只需知道它可以非常輕量級的處理HTTP請求,不用走繁瑣的頁面生命周期處理各種非必需數(shù)據(jù)。
Handler.ashx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using Newtonsoft.Json;namespace Web { /// <summary> /// Summary description for Handler /// </summary> public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { Student stu = new Student(); int Id = Convert.ToInt32(context.Request.Form["ID"]); if (Id == 1) { stu.Name = "Byron"; } else { stu.Name = "Frank"; } string stuJsonString= JsonConvert.SerializeObject(stu); context.Response.Write(stuJsonString); } public bool IsReusable { get { return false; } } } }
關(guān)于這個類語法本文不做詳細說明,每次發(fā)起HTTP請求ProcessRequest方法都會被調(diào)用到,Post類型請求參數(shù)和一再Request對象的Form中取得,每次根據(jù)參數(shù)ID值返回對應(yīng)json對象字符串,為了展示json格式數(shù)據(jù)交互,需要為項目引入json.net這一開源類庫處理對象序列化反序列化問題,然后創(chuàng)建一個Student類文件
Student.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Web { public class Student { public int ID { get; set; } public string Name { get; set; } } }
看看頁面如何處理
function testPost() { $.ajax({ type: 'post', url: 'Handler.ashx', async: true, data: { ID: '1' }, success: function (result) { setContainer(result); var stu =eval ('('+result+')'); setContainer(stu.ID); setContainer(stu.Name); }, error: function () { setContainer('ERROR!'); } }); }
結(jié)果是這個樣子的
上面代碼向Handler.ashx發(fā)送一Post請求,比且?guī)в袇?shù){ID:’1’},可以看到結(jié)果,如果用調(diào)試工具可以發(fā)現(xiàn),得到的result是一個json格式的字符串,也就是往Response寫的對象序列化后的結(jié)果。這樣就實現(xiàn)了比較專業(yè)些的方式調(diào)用Ajax,但是有一個問題依舊存在,HttpHandler會自動調(diào)用ProcessRequest方法,但是也只能調(diào)用該方法,如果想調(diào)用不同方法只能像普通頁面那樣傳遞一個參數(shù)表明調(diào)用哪個方法,或者寫不同的Handler文件。
WebService與ScriptManager
微軟向來很貼心,看看微軟怎么處理上面的困惑,那就是利用WebService,WebService配合SCriptManager有客戶端調(diào)用的能力,在項目中添加一個Webservice文件
WebService.asmx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Web { /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public Student GetStudent(int ID) { if (ID == 1) { return new Student() { ID = 1, Name = "Byron" }; } else { return new Student() { ID = 2, Name = "Frank" }; } }
[WebMethod] public string GetDateTime(bool isLong) { if (isLong) { return DateTime.Now.ToLongDateString(); } else { return DateTime.Now.ToShortDateString(); } } } }
代碼中加黃的code默認(rèn)是被注釋掉的,要想讓客戶端調(diào)用需要把注釋去掉,Service中定義了兩個方法,寫個測試方法讓客戶端調(diào)用第一個方法根據(jù)參數(shù)返回對應(yīng)對象,首先需要在頁面from內(nèi)加上ScriptManager,引用剛才寫的WebService文件
Default.aspx
<form id="form1" runat="server"> <asp:ScriptManager ID="clientService" runat="server"> <Services> <asp:ServiceReference Path="~/WebService.asmx" /> </Services> </asp:ScriptManager> <p id="container"> <input type="button" value="Test Ajax" onclick="testPost2()" /> <br /> </p>...
然后添加JavaScript測試代碼
function testPost2() { Web.WebService.GetStudent(1, function (result) { setContainer(result.ID); setContainer(result.Name); }, function () { setContainer('ERROR!'); }); }
測試代碼中需要顯示書寫WebService定義方法完整路徑,WebService命名空間.WebService類名.方法名,而出入的參數(shù)列表前幾個是調(diào)用方法的參數(shù)列表,因為GetStudent只有一個參數(shù),所以只寫一個,如果有兩個參數(shù)就順序?qū)憙蓚€,另外兩個參數(shù)可以很明顯看出來是響應(yīng)成功/失敗處理程序。看看執(zhí)行結(jié)果:
觀察仔細會發(fā)現(xiàn)使用ScriptManager和WebService組合有福利,在WebService中傳回Student對象的時候并沒有序列化成字符串,而是直接返回,看上面圖發(fā)現(xiàn)對象已經(jīng)自動轉(zhuǎn)換為一json對象,result結(jié)果可以直接操作,果真非常貼心。而上一個例子中我們得到的response是一個json字符串,在客戶端需要用eval使其轉(zhuǎn)換為json對象。
ScriptManager+WebSefvice調(diào)用ajax帶來了很大的便利性,但同時犧牲了很多靈活性,我們沒法像jQuery那樣指定很多設(shè)置有沒有兩全其美的辦法呢
$.ajax+WebService
jQuery調(diào)用Handler幾乎完美了,但是不能處理多個方法,上面例子我們可以發(fā)現(xiàn)WebService可以實現(xiàn)這一功能,那么能不能jQUery調(diào)用WebService的不同方法呢?答案是肯定的,試一試用jQuery調(diào)用剛才WebService定義的第二個方法。寫一個測試函數(shù)
function testPost3() { $.ajax({ type: 'post', url: 'WebService.asmx/GetDateTime', async: true, data: { isLong: true }, success: function (result) { setContainer($(result).find('string').text()); }, error: function () { setContainer('ERROR!'); } }); }
調(diào)用方式?jīng)]有多大變化,簡單依舊,只要把URL改為WebService路徑+需要調(diào)用的方法名,然后把參數(shù)放到data里就可以了。我們看看結(jié)果:
通過上圖可以看到,jQuery調(diào)用WebService默認(rèn)會返回一個XML文檔,而需要的數(shù)據(jù)在 <string>節(jié)點中,只需要使用jQuery解析xml的語法就可以輕松得到數(shù)據(jù)。如果希望返回一個json對象怎么辦?那就得和調(diào)用Handler一樣使用json.net序列化,然后前端使用eval轉(zhuǎn)換了,也不會過于復(fù)雜。我在項目中最常使用這個模式,這樣既保持了jQuery的靈活性又可以在一個Service中書寫多個方法供調(diào)用,還不用走復(fù)雜的頁面生命周期
json.net和本文示例源代碼
json.net是一個開源的.net平臺處理json的庫,可以序列化Dictionay嵌套等復(fù)雜對象,關(guān)于其簡單使用有時間會總結(jié)一下,可以自codeplex上得到其源碼和官方說明。本文的源代碼可以點擊這里獲得。
其他相關(guān)免費學(xué)習(xí)推薦:js視頻教程