DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
利用 ajaxpro.dll 進行 Ajax 開發的完整指南
編輯:AJAX詳解     

Ajax.NET 是 Ajax 技術在 .NET 框架下的實作,作者 Michael Schwarz 採用了相當出色的封裝手法:把客戶端處理 XML、事件呼叫的邏輯都封裝進兩個 JavaScript 檔(AjaxPro.prototype.js 與 AjaxPro.core.js),並將它們以資源形式編譯進 DLL,在處理客戶端對自訂 .ashx 檔的請求時再回傳這兩個檔案。因此使用 Ajax.NET 時,必須在 Web.config 註冊 httpHandler,交由 AjaxPro.AjaxHandlerFactory 處理 .ashx 檔:

<system.web>
  <httpHandlers>
    <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro" />
  </httpHandlers>
</system.web>

在此基礎上,Ajax.NET 會把要處理的方法加以封裝,以便客戶端透過 JavaScript 呼叫。首先在 converter.ashx 中完成方法封裝,以支援任意數量與型別的參數及回傳值,接著再封裝伺服器端邏輯方法所在的類別。

如何開始使用 Ajax.NET

A:到官網下載 Ajax.NET(本文以 6.4.15.1 版為例)。

B:解壓 zip,並在專案中加入對 DLL 的參考(AjaxPro.dll 為 .NET 1.1 版,AjaxPro.2.dll 為 2.0 版)。

C:如前面所述,在 web.config 中加入對 ashx 的處理設定。

D:在伺服器端加上要由 Ajax.NET 處理的方法。以下以「回傳輸入字串的 MD5 驗證碼」為例,先套用 [AjaxPro.AjaxMethod] 屬性:

[AjaxPro.AjaxMethod]
public string Md5Hash(string sSou)
{
    string sResult = "";
    byte[] byBuffer = System.Text.Encoding.UTF8.GetBytes(sSou);
    System.Security.Cryptography.MD5CryptoServiceProvider md = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] result = md.ComputeHash(byBuffer);
    for (int i = 0; i < result.GetLength(0); i++)
    {
        sResult += result[i].ToString("X2");
    }
    return sResult;
}

接著在 Page_Load 註冊此類別:

private void Page_Load(object sender, System.EventArgs e)
{
    AjaxPro.Utility.RegisterTypeForAjax(typeof(WebForm1));
}

E:在客戶端呼叫方法:

<script type="text/javascript">
function getMd5()
{
    var a = document.getElementById("source").value;
    var c = TAjax.WebForm1.Md5Hash(a);
    alert(c.value);
}
</script>
<input type="text" id="source" name="source" />
<input type="button" name="sub" onclick="getMd5()" value="提交" />

這裡的 TAjax.WebForm1 就是實作類別的完整名稱(含命名空間)。就這樣,一個簡單的 Ajax 應用便完成了。

無 aspx 檔的邏輯層與表現層分離

更進一步,Ajax.NET 甚至能實作「沒有 aspx 檔」的應用,徹底分離邏輯層與表現層。關鍵就在那幾個 JS 檔。啟動程式、檢視原始碼,奧妙就在這裡:

<script type="text/javascript" src="/TAjax/ajaxpro/prototype.ashx"></script>
<script type="text/javascript" src="/TAjax/ajaxpro/core.ashx"></script>
<script type="text/javascript" src="/TAjax/ajaxpro/converter.ashx"></script>
<script type="text/javascript" src="/TAjax/ajaxpro/TAjax.WebForm1,TAjax.ashx"></script>

註:TAjax 在 VB 中是專案名稱,在 C# 中則為命名空間名稱,WebForm1 為類名。前 3 個檔前面已說明,最後一個正是 Ajax.NET 對伺服器端類別的封裝:

addNamespace("TAjax");
TAjax.WebForm1_class = Class.create();
Object.extend(TAjax.WebForm1_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
    Md5Hash: function(sSou) {
        return this.invoke("Md5Hash", {"sSou":sSou}, this.Md5Hash.getArguments().slice(1));
    },
    initialize: function() {
        this.url = '/TAjax/ajaxpro/TAjax.WebForm1,TAjax.ashx';
    }
}));
TAjax.WebForm1 = new TAjax.WebForm1_class();

原理明白了,分離就簡單了。步驟從 D 開始調整:

D:新建一個類別 Admin,把原本在 WebForm1.aspx.cs 中的程式碼搬過來。以 VB.NET 為例,只需複製 Md5Hash 那段函式即可,不必再在构造函数中註冊:

<AjaxPro.AjaxMethod()> _
Public Function Md5Hash(ByVal sSou As String) As String
    Dim sResult As String = ""
    Dim byBuffer As Byte() = System.Text.Encoding.UTF8.GetBytes(sSou)
    Dim md As System.Security.Cryptography.MD5CryptoServiceProvider = New System.Security.Cryptography.MD5CryptoServiceProvider
    Dim result As Byte() = md.ComputeHash(byBuffer)
    Dim i As Integer
    For i = 0 To result.GetLength(0) - 1
        sResult += result(i).ToString("X2")
    Next
    Return sResult
End Function

E:新建一個 include.htm,把前述四行 JS 參照放進去;再建一個 test.htm 放客戶端表現層,並加入一個 iframe 引入 include.htm:

<iframe name="include" marginwidth="0" marginheight="0" src="include.htm" frameborder="0"></iframe>

呼叫方式改為透過 iframe 存取:

<script type="text/javascript">
function getMd5()
{
    var a = document.getElementById("source").value;
    var c = include.TAjax.Admin.Md5Hash(a);
    alert(c.value);
}
</script>

擴充:若多處呼叫且方法較長,可為每個業務類各做一個 JS 檔,把相關呼叫集中管理。

更多實用筆記

AjaxPro 上手簡單、實用性高、相容性也不錯。官網提供最新元件,下載後含 VS2005 模板,安裝即可直接建立 AjaxPro Website,內建的 Demo 足以讓你完全掌握用法。若使用 .NET 2.0 而不透過 VS2005,只要把 AjaxPro.2.dll 放進 bin 資料夾,並完成以下幾步即可:

1、在 system.web 節點下加入 httpHandler:

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

2、為 .NET 方法加上 AjaxMethod 屬性:

[AjaxPro.AjaxMethod]
public DateTime GetServerTime()
{
    return DateTime.Now;
}

3、在 Page_Load 中向客戶端註冊 JavaScript:

protected void Page_Load(object sender, EventArgs e)
{
    AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));
}

4、在客戶端以 JavaScript 呼叫:

function getServerTime()
{
    MyDemo._Default.GetServerTime(getServerTime_callback); // 非同步呼叫
}
function getServerTime_callback(res)
{
    alert(res.value);
}

幾個簡單步驟,就能在客戶端用 JavaScript 非同步呼叫伺服器端的 C# 方法並取得回傳值。回傳型別也不受限於 DateTime,DataTable 等複雜型別同樣能處理——AjaxPro 把 Ajax 變得非常簡單。值得一提的是 AjaxPro.OnLoading,可在伺服器尚未回值時向客戶端顯示載入中的提示。

用 AjaxPro 操作 Session

在伺服器端 Page_Load 註冊後,為方法加上 [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)] 屬性即可讀寫 Session:

[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
public void WriteSession(string str)
{
    Session["UserName"] = str;
}

[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
public string ReadSession()
{
    string str = "";
    if (Session["UserName"] != null)
        str = Session["UserName"].ToString();
    return str;
}

客戶端則透過回呼函式處理結果:

function WriteSession()
{
    test.WriteSession("HAHA", CallBack_WriteSession);
}
function CallBack_WriteSession(res)
{
    if (res.error == null) alert("OK");
    else alert(res.error.message);
}
function ReadSession()
{
    test.ReadSession(CallBack_ReadSession);
}
function CallBack_ReadSession(res)
{
    if (res.error == null) alert(res.value);
    else alert(res.error.message);
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved