【導讀】所謂的 Ajax 技術,號稱「無刷新」,其實是在 Web 上透過 JavaScript 發出非同步的 XMLHttp 請求,藉此實作出無刷新的網頁界面。本文透過一個實例,帶大家實際體驗 .NET Ajax 的無刷新技術。
先到 https://ajax.schwarz-interactive.de/ 下載一個 .NET Ajax 開發包,裡面同時包含 ASP.NET 2.0 與 ASP.NET 1.1 使用的 Ajax 版本。準備好之後就開始吧。
新建一個專案,在「加入參考」中把 Ajax.dll 引用進來。這個 DLL 就在下載回來的壓縮包裡。
在 web.config 中加入 HttpHandler 設定:
<configuration>
<system.web>
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
</system.web>
</configuration>
新增一個類別 DemoMethods,用來取得用戶端的 MAC 位址(這裡只是測試用,你也可以換成其他更簡單的函式):
using System;
using System.Web;
namespace AjaxSample
{
/// <summary>
/// 方法集合
/// </summary>
public class DemoMethods
{
[Ajax.AjaxMethod]
public string GetCustomerMac(string clientIP)
{
string mac = "";
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "nbtstat";
process.StartInfo.Arguments = "-a " + clientIP;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
int length = output.IndexOf("Mac Address = ");
if (length > 0)
{
mac = output.Substring(length + 14, 17);
}
process.WaitForExit();
return mac.Replace("-", "").Trim();
}
}
}
新增一個名為 default.js 的文件:
function GetMac()
{
var clientIP = "192.168.0.1";
alert(DemoMethods.GetCustomerMac(clientIP).value);
}
在某个 ASPX 页面放上一个 HTML 按钮,并在 <head> 中引用 default.js:
<script language="Javascript" src="default.js"></script>
在 INPUT 的 onclick 事件中挂上调用:
<input type="button" value="取得用戶端 MAC" onclick="GetMac();" />
private void Page_Load(object sender, System.EventArgs e)
{
// 在此注册要暴露给 Ajax 的类型
Ajax.Utility.RegisterTypeForAjax(typeof(AjaxSample.DemoMethods));
}
注意:typeof(AjaxSample.DemoMethods) 中的 AjaxSample 是命名空间,DemoMethods 是包含待调用方法的类,也就是步骤三所建的类。
修改 Global.asax 的 Application_Start 事件,指定 Ajax 的 HandlerPath:
protected void Application_Start(Object sender, EventArgs e)
{
Ajax.Utility.HandlerPath = "Ajax";
}
执行看看效果——是不是没有刷新,就已经从服务器端取回用户端的 MAC 位址了?
要特别留意:这个版本的 .NET Ajax 必须手动在 Global.asax 的 Application_Start 中加入 Ajax.Utility.HandlerPath = "Ajax";,而且 web.config 也一定要补上 HttpHandler 的设定信息。新版本据说会简化这些手动步骤,届时应该会方便许多。