本範例示範純前端 XMLHttpRequest(AJAX)呼叫後端 .aspx 頁面執行資料庫插入,無需 UpdatePanel、無需 WebMethod/PageMethod、無需 WCF/Web API。適合舊版 ASP.NET WebForms 專案快速加入無刷新互動。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX 插入範例</title>
<script type="text/javascript">
function insertData() {
// 1. 建立 XMLHttpRequest(相容 IE6+)
var xhr;
if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
alert("瀏覽器不支援 AJAX");
return;
}
// 2. 註冊回調
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert("插入成功!伺服器回應:" + xhr.responseText);
} else {
alert("請求失敗:" + xhr.status);
}
}
};
// 3. 取得表單值
var no = document.getElementById("TextBox1").value;
var name = document.getElementById("TextBox2").value;
// 4. 發送 GET 請求(含查詢字串參數)
var url = "Default2.aspx?no=" + encodeURIComponent(no) + "&name=" + encodeURIComponent(name);
xhr.open("GET", url, true); // true = 非同步
xhr.send(null);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
號碼:<asp:TextBox ID="TextBox1" runat="server" /><br />
姓名:<asp:TextBox ID="TextBox2" runat="server" /><br />
<input type="button" value="AJAX 插入" onclick="insertData()" />
</div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX 處理端</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
InsertCommand="INSERT INTO [tst] ([no], [name]) VALUES (@no, @name)"
SelectCommand="SELECT * FROM [tst]">
<InsertParameters>
<asp:Parameter Name="no" Type="Int32" />
<asp:Parameter Name="name" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
public partial class Default2 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
// 1. 從 QueryString 取得參數
string no = Request.QueryString["no"];
string name = Request.QueryString["name"];
// 2. 基本驗證(實務應加強:SQL 注入雖參數化已防,但仍需驗證格式、長度、權限)
if (string.IsNullOrEmpty(no) || string.IsNullOrEmpty(name)) {
Response.Write("參數缺失");
Response.End();
return;
}
// 3. 設定 SqlDataSource 參數並執行插入
SqlDataSource1.InsertParameters["no"].DefaultValue = no;
SqlDataSource1.InsertParameters["name"].DefaultValue = name;
try {
int affected = SqlDataSource1.Insert();
Response.Write($"成功插入 {affected} 筆資料");
} catch (Exception ex) {
Response.Write("插入失敗:" + ex.Message);
// 實務應記錄 Log,不直接輸出錯誤細節
}
}
}
| 環節 | 說明 | 注意事項 |
|---|---|---|
| XMLHttpRequest 建立 | 相容 ActiveXObject (IE6/7) 與標準 XHR | 現代專案建議直接用 fetch() 或 axios |
| 參數傳遞 | QueryString (GET) 或 FormData (POST) | GET 有長度限制、敏感資料不可用;實務建議 POST |
| 編碼 | encodeURIComponent() 處理中文/特殊字元 | 後端 Request.QueryString 自動解碼 |
| SqlDataSource 參數化 | InsertParameters 對應 @no, @name | 自動防 SQL 注入,型別轉換 |
| 回應格式 | 純文字/HTML 片段/JSON | 建議統一回傳 JSON:{success: true, msg: ""} |
| 錯誤處理 | try-catch 包裹 Insert() | 記錄完整堆疊至 Log,前端僅顯示友善訊息 |
// 前端
xhr.open("POST", "Default2.aspx", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("no=" + encodeURIComponent(no) + "&name=" + encodeURIComponent(name));
// 後端
if (Request.HttpMethod == "POST") {
string no = Request.Form["no"];
string name = Request.Form["name"];
// ... 執行插入 ...
Response.ContentType = "application/json";
Response.Write("{\"success\": true, \"message\": \"插入成功\"}");
Response.End();
}
$.post("Default2.aspx", { no: $("#TextBox1").val(), name: $("#TextBox2").val() })
.done(function(data) { alert(data.message); })
.fail(function() { alert("請求失敗"); });
ApiController(需安裝 Microsoft.AspNet.WebApi NuGet)。config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");IHttpActionResult,自動 JSON 序列化、內容協商、模型驗證。/api/Items,關注點分離、可單元測試、支援 Swagger 文件。<input type="hidden" id="csrfToken" value="..." />,AJAX 送出時帶入 Header X-CSRF-Token,後端驗證。customErrors mode="RemoteOnly",Log 記錄完整異常。