架構總覽
前端 (jQuery) 後端 (ASHX)
│ │
├─ $.ajax({dataType:'json'}) ───►│
│ POST /api/Handler.ashx │
│ Content-Type: application/json│
│ {param: "value"} │
│ ├─ context.Request["param"]
│ ├─ 處理邏輯
│ ├─ 物件 → JSON (Json.NET)
│ ├─ context.Response.ContentType = "application/json"
│ └─ context.Response.Write(json)
│◄─── {success:true, data:{...}}─┤
│ │
└─ success: function(resp) { │
resp.data → 更新 UI │
} │
前端 jQuery AJAX 封裝
/**
* 統一 AJAX 封裝
* @param {string} url - .ashx 路徑
* @param {Object} data - 參數物件
* @param {Function} onSuccess - 成功回調 (接收解包後的 data)
* @param {Function} onError - 失敗回調
*/
function apiPost(url, data, onSuccess, onError) {
var $loading = $('#loadingIndicator'); // 可選:載入指示器
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data || {}),
timeout: 30000,
beforeSend: function() {
$loading.show();
$(document).trigger('ajaxStart');
},
complete: function() {
$loading.hide();
$(document).trigger('ajaxStop');
},
success: function(response, textStatus, xhr) {
// 統一處理後端回傳格式:{ success: true, data: ..., message: ... }
if (response && response.success === true) {
onSuccess && onSuccess(response.data, response.message);
} else {
var msg = (response && response.message) || '操作失敗';
onError && onError(msg, response);
// 可選:全域錯誤提示
// $.notify(msg, 'error');
}
},
error: function(xhr, status, error) {
var msg = '請求異常';
if (xhr.responseJSON && xhr.responseJSON.message) {
msg = xhr.responseJSON.message;
} else if (xhr.status === 0) {
msg = '網路連線失敗';
} else if (xhr.status === 401) {
msg = '登入已過期,請重新登入';
// 導向登入頁
} else if (xhr.status === 500) {
msg = '伺服器內部錯誤';
}
onError && onError(msg, xhr);
}
});
}
// 使用範例
apiPost('/api/SaveData.ashx', {
id: 123,
name: '測試',
tags: ['a', 'b']
}, function(data) {
console.log('儲存成功,回傳 ID:', data.newId);
refreshGrid();
}, function(msg) {
alert(msg);
});
後端 ASHX 處理器 (C#)
<%@ WebHandler Language="C#" Class="SaveDataHandler" %>
using System;
using System.Web;
using System.Web.Script.Serialization; // 內建 (較舊)
using Newtonsoft.Json; // 推薦:Json.NET (NuGet)
using Newtonsoft.Json.Converters;
public class SaveDataHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
try {
// 1. 讀取請求體 (JSON)
string jsonBody;
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) {
jsonBody = reader.ReadToEnd();
}
// 2. 反序列化 (支援動態型別)
dynamic req = JsonConvert.DeserializeObject(jsonBody);
int id = req.id;
string name = req.name;
var tags = req.tags?.ToObject() ?? new string[0];
// 3. 業務邏輯
// var result = BusinessLayer.Save(id, name, tags);
var result = new { newId = id > 0 ? id : new Random().Next(1000, 9999), savedAt = DateTime.Now };
// 4. 序列化回應 (統一格式)
var response = new {
success = true,
data = result,
message = "儲存成功"
};
// 日期格式化:ISO 8601 (前端 new Date() 可直接解析)
var settings = new JsonSerializerSettings {
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
context.Response.Write(JsonConvert.SerializeObject(response, settings));
} catch (Exception ex) {
// 統一錯誤格式
var errorResponse = new {
success = false,
message = "處理失敗:" + ex.Message
// 生產環境不應暴露堆疊追蹤
};
context.Response.StatusCode = 500;
context.Response.Write(JsonConvert.SerializeObject(errorResponse));
}
}
public bool IsReusable { get { return false; } }
}
關鍵技術細節
1. Content-Type 必須匹配
| 前端發送 | 後端讀取 | 適用場景 |
| application/json | Request.InputStream + JSON 反序列化 | 複雜物件、巢狀結構、陣列 (推薦) |
| application/x-www-form-urlencoded | Request["key"] / Request.Form["key"] | 簡單鍵值對、傳統表單提交 |
| multipart/form-data | Request.Files / Request.Form | 檔案上傳 |
2. 日期時間序列化陷阱
// ❌ 錯誤:預設 JavaScriptSerializer 產生 "/Date(1234567890123)/"
// 前端需手動解析
// ✅ 正確:Json.NET + IsoDateTimeConverter
var settings = new JsonSerializerSettings {
DateFormatHandling = DateFormatHandling.IsoDateFormat, // "2024-01-15T08:30:00Z"
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
// ✅ 或自訂格式
var converter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
JsonConvert.SerializeObject(obj, converter);
3. 錯誤處理統一格式
// 成功
{ "success": true, "data": {...}, "message": "操作成功" }
// 失敗 (驗證錯誤)
{ "success": false, "data": null, "message": "姓名不可為空", "errors": { "name": "必填" } }
// 失敗 (系統錯誤)
{ "success": false, "data": null, "message": "伺服器內部錯誤", "code": 500 }
常見問題排查
| 現象 | 原因 | 解決 |
| 前端收到 HTML 而非 JSON | ASHX 拋出黃色死機頁面 (YSOD) | try-catch 捕獲所有異常,輸出 JSON 錯誤格式 |
| data 為 undefined | 後端未設定 Content-Type: application/json | context.Response.ContentType = "application/json" |
| 中文亂碼 | 編碼不一致 | 前後端統一 UTF-8,Request.ContentEncoding 正確 |
| 大數據傳輸超時 | 預設 timeout 過短 | 調整 $.ajax timeout、IIS executionTimeout、web.config httpRuntime |
| 重複提交 | 使用者連點按鈕 | 按鈕 loading 狀態禁用、後端冪等性設計 (Token) |
現代化遷移建議
- ASP.NET Core Minimal API:
app.MapPost("/api/save", async (SaveDto dto) => ...),自動模型綁定、驗證、OpenAPI 文檔
- Controller + [ApiController]:屬性路由、模型驗證、問題詳情
- 前端改用 fetch/axios:Promise、攔截器、TypeScript 型別安全
- 統一結果封裝:
Result<T> 模式替代手工 JSON 構建
總結
jQuery AJAX + ASHX + JSON.NET 是經典 ASP.NET Web Forms 時代的標準整合模式。核心要點:統一 Content-Type、JSON 序列化用 Json.NET、日期用 ISO 8601、錯誤格式標準化、前端統一封裝。維護舊專案時遵循此模式可大幅減少 Bug;新專案請直接採用 ASP.NET Core Web API + 現代前端框架,獲得開發效能與維護性的雙重提升。