前端呼叫 .ashx 處理 AJAX 請求時,可使用原生 XMLHttpRequest 或 jQuery 封裝方法。本文對比兩種寫法,說明參數傳遞、回應處理、錯誤捕捉差異。
var xhr = new XMLHttpRequest();
var cartId = document.getElementById("txtCartId").value;
var count = document.getElementById("txtCount").value;
var url = "Controls/gengCart.ashx?CartID=" + encodeURIComponent(cartId)
+ "&count=" + encodeURIComponent(count);
xhr.open("GET", url, true); // 非同步
xhr.setRequestHeader("If-Modified-Since", "0"); // 防止 IE 快取 GET 請求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var result = xhr.responseText;
try {
var json = JSON.parse(result); // 建議用 JSON.parse,避免 eval 風險
alert(json.name);
} catch (e) {
console.error("JSON 解析失敗", e);
}
} else {
console.error("請求失敗", xhr.status);
}
}
};
xhr.send(null);
$.ajax({
url: 'Controls/Cart.ashx',
type: 'POST', // 或 GET
data: {
productID: <%= GetID %>,
count: 1,
userID: '<%= uid %>'
},
dataType: 'json', // 自動解析 JSON 回應
success: function (data, textStatus, jqXHR) {
if (data === "success" || data.success) {
window.location = "gwc.aspx?uid=" + '<%= uid %>';
} else if (data === "false" || data.error) {
alert("請先登入");
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("AJAX 錯誤", textStatus, errorThrown);
}
});
| 特性 | 原生 XMLHttpRequest | jQuery $.ajax |
|---|---|---|
| 程式碼量 | 較多,需手動處理狀態、標頭、編碼 | 簡潔,鏈式呼叫、預設值豐富 |
| JSON 解析 | 手動 JSON.parse | dataType: 'json' 自動 |
| 錯誤處理 | 需檢查 readyState、status | 統一 error 回呼 |
| 快取控制 | 手動設定標頭 | cache: false 參數 |
| FormData 支援 | 手動建構 | processData: false, contentType: false 直接傳 FormData |
| Promise/async-await | 需自行封裝 | 回傳 jqXHR (Promise-like),可 await $.ajax(...) |
| 跨瀏覽器 | 現代瀏覽器一致,IE6/7 需 ActiveXObject | 內建處理 IE 相容 |
public void ProcessRequest(HttpContext context)
{
// GET 參數
string cartId = context.Request.QueryString["CartID"];
// POST 參數
string productId = context.Request.Form["productID"];
// 統一取值 (QueryString + Form)
string count = context.Request["count"];
// 回傳 JSON
context.Response.ContentType = "application/json";
context.Response.Write("{\"name\":\"Test\"}");
}
$.ajax 或 $.post/$.get 簡化代碼。fetch API(現代瀏覽器)或 XMLHttpRequest。encodeURIComponent 編碼 URL 參數,防止特殊字元錯誤。Content-Type: application/json,前端 dataType: 'json' 自動解析。