前端需呼叫 .ashx 泛型處理常式,取得包含二進位資料(如圖片 Base64、檔案流)的 JSON 字串,並正確解析使用。許多開發者在 dataType: 'json' 設定下,發現二進位欄位變成亂碼或無法存取。
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script>
$.ajax({
url: 'YourHandler.ashx',
dataType: 'json', // 自動解析 JSON 為 JavaScript 物件
type: 'GET', // 或 POST,視後端而定
success: function (json) {
// json 為已解析的物件,直接存取屬性
console.log('完整回應:', json);
// 若二進位資料為 Base64 字串
if (json.imageBase64) {
$('#imgPreview').attr('src', 'data:image/png;base64,' + json.imageBase64);
}
// 若為 byte 陣列(需後端序列化為數字陣列)
if (json.byteArray) {
var bytes = new Uint8Array(json.byteArray);
// 進一步處理,如建立 Blob 下載
}
},
error: function (xhr, status, err) {
console.error('AJAX 錯誤:', status, err);
alert('請求失敗或 JSON 格式錯誤: ' + xhr.responseText);
}
});
</script>
JSON.parse,回呼函式直接收到物件,無需手動解析。[72, 101, 108, ...]),不可直接輸出原始位元組,否則 JSON 序列化會失敗或產生無效字元。error 回呼可攔截網路錯誤、HTTP 非 2xx 狀態、JSON 解析失敗等情況。| 現象 | 原因 | 解決 |
|---|---|---|
收到 parsererror | ASHX 輸出非標準 JSON(如多餘 Response.Write、HTML 註解) | 確保 context.Response.ContentType = "application/json",且只輸出純 JSON |
二進位欄位為 null 或亂碼 | 直接序列化 byte[] 導致無效 Unicode | 後端用 Convert.ToBase64String(bytes) 或 bytes.Select(b => (int)b).ToArray() |
| 跨域被瀏覽器攔截 | ASHX 未加入 CORS 標頭 | 在 ProcessRequest 加入 context.Response.Headers.Add("Access-Control-Allow-Origin", "*") |
public class YourHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json";
// 跨域支援(視需求)
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var data = new {
id = 123,
fileName = "demo.png",
imageBase64 = Convert.ToBase64String(File.ReadAllBytes(context.Server.MapPath("~/App_Data/demo.png")))
};
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
context.Response.Write(json);
}
public bool IsReusable => false;
}
掌握「前端 dataType: 'json' 自動解析」與「後端二進位 Base64/陣列序列化」兩大核心,即可輕鬆實現 ASHX 回傳 JSON 含二進位資料的穩健互動。