AJAX表單驗證項目實戰(zhàn)之實時用戶名檢查功能
更新時間:2025年08月08日 10:03:15 作者:白侖色
在Web開發(fā)中,表單驗證是確保用戶輸入有效性的關(guān)鍵步驟,它不僅提高了數(shù)據(jù)質(zhì)量,還能增強系統(tǒng)的安全性,這篇文章主要介紹了AJAX表單驗證項目實戰(zhàn)之實時用戶名檢查功能的相關(guān)資料,需要的朋友可以參考下
項目概述
本項目實現(xiàn)一個注冊頁面的用戶名實時驗證功能,使用AJAX技術(shù)在用戶輸入時異步檢查用戶名是否已被占用,提供即時反饋。
技術(shù)棧
- 前端:HTML5, CSS3, JavaScript (原生AJAX)
- 后端:Python Flask
- 數(shù)據(jù)存儲:簡單文本文件存儲已注冊用戶名
功能需求
- 用戶在注冊表單輸入用戶名
- 輸入框失去焦點或用戶停止輸入后自動觸發(fā)檢查
- 實時顯示"用戶名可用"或"用戶名已被占用"提示
- 顯示加載狀態(tài)指示正在檢查
項目結(jié)構(gòu)
ajax-form-validation/ ├── static/ │ ├── css/ │ │ └── style.css # 樣式文件 │ └── js/ │ └── script.js # AJAX邏輯 ├── templates/ │ └── index.html # 注冊表單頁面 ├── data/ │ └── users.txt # 存儲已注冊用戶名 └── app.py # Flask后端
前端設(shè)計
HTML結(jié)構(gòu)
- 注冊表單包含用戶名、密碼等字段
- 用戶名輸入框添加事件監(jiān)聽
- 提示信息區(qū)域用于顯示驗證結(jié)果
CSS樣式
- 輸入框狀態(tài)樣式(正常、驗證中、有效、無效)
- 提示信息樣式(成功、錯誤、加載中)
- 響應(yīng)式設(shè)計適配不同設(shè)備
JavaScript邏輯
- 使用addEventListener監(jiān)聽輸入事件
- 實現(xiàn)AJAX請求函數(shù)
- 處理服務(wù)器響應(yīng)并更新UI
- 添加防抖處理避免頻繁請求
后端設(shè)計
API接口
- GET /check-username?username=xxx 檢查用戶名是否存在
- 返回JSON格式響應(yīng):{ “available”: true/false }
數(shù)據(jù)處理
- 從users.txt讀取已注冊用戶名
- 檢查請求的用戶名是否存在
- 返回檢查結(jié)果
以下是代碼:
- index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用戶注冊 - AJAX表單驗證示例</title>
<link rel="stylesheet" href="../static/css/style.css" rel="external nofollow" />
</head>
<body>
<div class="container">
<h1>用戶注冊</h1>
<form id="registerForm">
<div class="form-group">
<label for="username">用戶名:</label>
<div class="input-group">
<input type="text" id="username" name="username" required
minlength="3" maxlength="20" placeholder="請輸入用戶名">
<div id="usernameFeedback" class="feedback"></div>
</div>
<small>用戶名長度為3-20個字符</small>
</div>
<div class="form-group">
<label for="password">密碼:</label>
<input type="password" id="password" name="password" required
minlength="6" placeholder="請輸入密碼">
</div>
<div class="form-group">
<label for="email">郵箱:</label>
<input type="email" id="email" name="email" required placeholder="請輸入郵箱">
</div>
<button type="submit" id="submitBtn">注冊</button>
</form>
</div>
<script src="../static/js/script.js"></script>
</body>
</html>
- style.css
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Arial', sans-serif;
}
body {
background-color: #f5f5f5;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 20px;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
}
h1 {
text-align: center;
margin-bottom: 25px;
color: #333;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #555;
font-weight: 500;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #4CAF50;
box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}
.input-group {
position: relative;
}
.feedback {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
font-size: 14px;
display: none;
}
.feedback.loading {
color: #999;
display: inline;
}
.feedback.available {
color: #4CAF50;
display: inline;
}
.feedback.unavailable {
color: #F44336;
display: inline;
}
small {
display: block;
margin-top: 5px;
color: #777;
font-size: 12px;
}
button {
width: 100%;
padding: 12px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
- script.js
document.addEventListener('DOMContentLoaded', function() {
const usernameInput = document.getElementById('username');
const feedbackElement = document.getElementById('usernameFeedback');
const submitBtn = document.getElementById('submitBtn');
let isUsernameAvailable = false;
// 防抖函數(shù)
function debounce(func, delay = 500) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
// 檢查用戶名
function checkUsername() {
const username = usernameInput.value.trim();
// 如果用戶名為空,不檢查
if (!username) {
feedbackElement.style.display = 'none';
isUsernameAvailable = false;
updateSubmitButton();
return;
}
// 顯示加載狀態(tài)
feedbackElement.textContent = '檢查中...';
feedbackElement.className = 'feedback loading';
// 創(chuàng)建AJAX請求
const xhr = new XMLHttpRequest();
xhr.open('GET', `/check-username?username=${encodeURIComponent(username)}`, true);
xhr.onload = function() {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
if (response.available) {
feedbackElement.textContent = '用戶名可用';
feedbackElement.className = 'feedback available';
isUsernameAvailable = true;
} else {
feedbackElement.textContent = '用戶名已被占用';
feedbackElement.className = 'feedback unavailable';
isUsernameAvailable = false;
}
} catch (e) {
feedbackElement.textContent = '檢查失敗,請重試';
feedbackElement.className = 'feedback unavailable';
isUsernameAvailable = false;
}
} else {
feedbackElement.textContent = '服務(wù)器錯誤,請稍后再試';
feedbackElement.className = 'feedback unavailable';
isUsernameAvailable = false;
}
updateSubmitButton();
};
xhr.onerror = function() {
feedbackElement.textContent = '網(wǎng)絡(luò)錯誤,請檢查連接';
feedbackElement.className = 'feedback unavailable';
isUsernameAvailable = false;
updateSubmitButton();
};
xhr.send();
}
// 更新提交按鈕狀態(tài)
function updateSubmitButton() {
submitBtn.disabled = !isUsernameAvailable || !usernameInput.value.trim();
}
// 監(jiān)聽輸入事件,使用防抖
usernameInput.addEventListener('input', debounce(checkUsername));
// 監(jiān)聽失焦事件
usernameInput.addEventListener('blur', checkUsername);
// 表單提交處理
document.getElementById('registerForm').addEventListener('submit', function(e) {
e.preventDefault();
if (isUsernameAvailable) {
// 這里可以添加表單提交邏輯
alert('注冊成功!');
}
});
});
運行結(jié)果:
data.txt文件中有admin用戶名的情況下
用戶名存在的情況下,注冊不了

用戶名不存在的情況下,注冊成功

總結(jié)
到此這篇關(guān)于AJAX表單驗證項目實戰(zhàn)之實時用戶名檢查功能的文章就介紹到這了,更多相關(guān)AJAX實時用戶名檢查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
使用Ajax進行文件與其他參數(shù)的上傳功能(java開發(fā))
這篇文章主要介紹了使用Ajax進行文件與其他參數(shù)的上傳功能(java開發(fā)),非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-01-01
herf=#導(dǎo)致Ajax請求時沒有向后臺發(fā)送數(shù)據(jù)
當點擊重命名進行Ajax請求時,并沒有向后臺發(fā)送數(shù)據(jù)而是直接跳轉(zhuǎn)到了首頁,后來發(fā)現(xiàn)是這個herf=#惹的禍2014-05-05

