示範兩種 AJAX 即時檢查用戶名可用性的做法:原生 XMLHttpRequest 封裝與 jQuery $.ajax,後端以 `ASHX` 或 `ASPX` 處理請求,回傳純文字訊息。
function ajax(opt) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET", opt.url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) opt.success(xhr);
else opt.error(xhr);
}
};
xhr.send(null);
}
function checkUser() {
var name = document.getElementById("txtUser").value;
ajax({
url: "CheckUser.ashx?name=" + encodeURIComponent(name),
success: function(xhr) { alert(xhr.responseText); },
error: function(xhr) { alert("錯誤:" + xhr.status); }
});
}
$("#txtUser").on("blur", function() {
var name = $(this).val();
if (!name) return;
$.get("CheckUser.ashx", { name: name }, function(msg) {
$("#msg").text(msg).toggleClass("error", msg.indexOf("存在") >= 0);
});
});
public class CheckUser : IHttpHandler {
public bool IsReusable => true;
public void ProcessRequest(HttpContext context) {
string name = context.Request["name"];
if (string.IsNullOrEmpty(name)) return;
context.Response.ContentType = "text/plain; charset=utf-8";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
// 示範:實際應查詢資料庫
bool exists = name == "admin"; // 模擬
context.Response.Write(exists
? "用戶名已存在,請換一個"
: "用戶名可用");
}
}
protected void Page_Load(object sender, EventArgs e) {
if (!string.IsNullOrEmpty(Request["name"])) {
Response.Clear();
Response.ContentType = "text/plain";
Response.Write(Request["name"] == "admin" ? "已存在" : "可用");
Response.End(); // 關鍵:結束生命週期,避免輸出頁面 HTML
}
}
[HttpGet("api/check-username")]
public IActionResult Check(string username) {
bool exists = _userService.Exists(username);
return Json(new { valid = !exists, message = exists ? "已存在" : "可用" });
}