前端:jQuery + ScriptManager 代理調用 ASMX WebService。
後端:C# WebMethod 返回 JSON 字符串,判斷郵箱是否存在。
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>郵箱異步驗證</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" />
</Services>
</asp:ScriptManager>
<div>
<label>郵箱:<input type="email" id="txtUsername" /></label>
<span id="emailMsg" style="margin-left:10px;color:red;"></span>
</div>
</form>
<script>
$(function() {
$('#txtUsername').on('blur', function() {
var email = $.trim($(this).val());
if (!email) return;
// 顯示檢查中
$('#emailMsg').text('驗證中...').css('color', '#999');
// 調用 WebService(ScriptManager 生成的代理類)
// 命名空間.類名.方法名(參數, 成功回調, 失敗回調)
SinaWeiBo.WebService1.cunzai(email,
function(result) { // 成功回調
if (result === "該郵箱已存在請重新輸入") {
$('#emailMsg').text(result).css('color', 'red');
$(this).val('').focus(); // 清空並聚焦
} else {
$('#emailMsg').text('可以使用').css('color', 'green');
}
}.bind(this), // 綁定 this 為 input 元素
function(error) { // 失敗回調
$('#emailMsg').text('驗證失敗:' + error.get_message()).css('color', 'red');
}
);
});
});
</script>
</body>
</html>
using System;
using System.Web.Services;
using System.Data;
namespace SinaWeiBo
{
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] // 關鍵:允許腳本調用
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string cunzai(string txtusername)
{
try
{
// 假設 BLL 層查詢
// BLL.T_Users bt1 = new BLL.T_Users();
// DataSet ds = bt1.GetList("T_UserEmail='" + txtusername + "'");
// 模擬數據
var existingEmails = new[] { "test@test.com", "admin@example.com" };
if (Array.Exists(existingEmails, e => e.Equals(txtusername, StringComparison.OrdinalIgnoreCase))) {
return "該郵箱已存在請重新輸入";
}
return "正確"; // 或返回 "可以使用"
}
catch (Exception ex)
{
// 記錄日誌
return "服務器錯誤:" + ex.Message;
}
}
}
}
ASMX 屬於舊技術棧。新項目建議使用:
ScriptManager + ASMX 是 ASP.NET WebForms 時代的產物,理解其原理有助於維護老項目。新開發請毫不猶豫選擇 Web API + 現代前端工具鏈。