單一 Handler 處理多個 AJAX 請求,傳統 switch(action) 變數作用域受限。解決方案:靜態 Dictionary<string, Func<string>> 映射 Action 至委派。
static Dictionary<string, Func<string>> hs;
static Handler() {
hs = new Dictionary<string, Func<string>>();
hs.Add("add", delegate() {
int id = int.Parse(req("id"));
string title = req("title");
return "add";
});
hs.Add("update", delegate() { ... });
}
public void ProcessRequest(HttpContext context) {
string action = context.Request["action"].ToLower();
string result = hs[action]();
context.Response.Write(result);
}
優點:各委派擁有獨立作用域、避免反射效能損失、程式碼結構清晰。
context.Response.Redirect("login.html") 會導致 AJAX 收到登入頁 HTML 而非預期資料。解決方案:
"unlogin")ajaxSuccess 全域攔截:優先檢查 xhr.responseText == "unlogin",再執行局部 success callbacksuccess() 內部邏輯順序此法統一處理所有 AJAX 請求的未登入導向,避免每個 callback 重複判斷。