核心邏輯
- 使用者輸入 Email 離開欄位
onBlur 觸發驗證
- 前端 AJAX 傳送 Email 至後端
mail.php
- 後端查詢資料庫回傳 0(已存在)或 1(可用)
- 前端顯示對應提示訊息
前端 JavaScript
function mailbox(strEmail) {
var name = document.blooger[0].email.value;
$.ajax({
type: "GET",
url: "mail.php", // 實際專案應用絕對路徑
data: "youx=" + name,
success: function(datax) {
var xx = document.getElementsByName("email")[0].value;
var $msg = $("#mailbox_msg");
if (xx === "") {
$msg.html('<font color="red">郵箱不能為空!</font>');
} else if (/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(xx)) {
if (datax == "0") {
$msg.html('<font color="red">郵箱已經被註冊</font>');
} else {
$msg.html('<font color="green">郵箱可以使用!</font>');
}
} else {
$msg.html('<font color="red">郵箱地址不正確</font>');
}
}
});
}
function check() {
// 表單提交前驗證
if (ee !== "1") { mailbox(); return false; }
}
HTML 表單
<form name="blooger" action="blogger.php?action=update" method="post" onsubmit="return check();">
<li>電子郵件
<input type="text" name="email" id="id_mailbox" style="width:185px" maxlength="200" onBlur="mailbox(this.value);" />
<span id="mailbox_msg"></span>
</li>
<li><input type="submit" value="保存資料" class="button" /></li>
</form>
後端 mail.php 邏輯(PHP 範例)
<?php
$email = $_GET['youx'];
// 查詢資料庫
$sql = "SELECT COUNT(*) FROM users WHERE email = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$email]);
$count = $stmt->fetchColumn();
echo ($count > 0) ? "0" : "1"; // 0=已存在, 1=可用
?>
改進建議
- 使用
$.get() 或 $.post() 簡化 AJAX 代碼
- 後端回傳 JSON:
{"available": true},前端 dataType: "json" 自動解析
- 加入防抖動:
setTimeout 延遲 300ms 發送請求
- 使用
fetch API 或 axios 替代 jQuery AJAX(現代專案)