Web.config 設定
<system.web>
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
</system.web>
伺服器端類別撰寫
public class MyService
{
[Ajax.AjaxMethod(HttpSessionStateRequirement.Read)]
public string GetResult(string hl, string jine)
{
try {
// 業務邏輯...
return (decimal.Parse(hl) * decimal.Parse(jine)).ToString();
}
catch { return null; }
}
}
頁面註冊
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(MyService));
}
前端 JavaScript 呼叫
function GetInformation() {
var hl = document.getElementById('DropDownList1').value;
var jine = document.getElementById('txtJine').value;
var result = MyService.GetResult(hl, jine); // 同步呼叫
document.getElementById('txtZhrmb').value = result.value;
}
// 非同步回呼版本
function GetInformationAsync() {
MyService.GetResult(hl, jine, Callback);
}
function Callback(response) {
if (response.error) alert(response.error);
else document.getElementById('txtZhrmb').value = response.value;
}
注意事項
- Ajax.dll 為第三方開源庫(Michael Schwarz),非微軟官方 ASP.NET AJAX。
- 僅支援 .NET 1.1/2.0 早期專案維護,新專案請改用 ASP.NET AJAX (ScriptManager) 或 ASP.NET Core SignalR/WebAPI。
- 方法必須為
public,參數/回傳型別需可序列化(基本型別、DataSet、可序列化類別)。