首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP + jQuery + AJAX 實現用戶名即時驗證

     編輯:PHP 相關知識

前端頁面 register.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用戶名驗證演示</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <style>
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <h2>註冊表單</h2>
    <form id="regForm" action="register.php" method="post">
        <div>
            <label>用戶名: </label>
            <input type="text" id="username" name="username" required>
            <span id="usernameTip"></span>
        </div>
        <div>
            <label>密碼: </label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">提交註冊</button>
    </form>

    <script>
    $(function() { // 等同 $(document).ready()
        $('#username').on('blur', function() {
            var username = $(this).val().trim();
            if (!username) {
                $('#usernameTip').html('<span class="error">用戶名不能為空</span>');
                return;
            }

            $.post('check_user.php', {username: username}, function(result) {
                // 後端約定:返回 JSON {exists: true/false, msg: '...'}
                try {
                    var res = typeof result === 'string' ? JSON.parse(result) : result;
                    if (res.exists) {
                        $('#usernameTip').html('<span class="error">' + (res.msg || '用戶名已存在') + '</span>');
                    } else {
                        $('#usernameTip').html('<span class="success">' + (res.msg || '用戶名可用') + '</span>');
                    }
                } catch (e) {
                    $('#usernameTip').html('<span class="error">服務器響應異常</span>');
                }
            }).fail(function() {
                $('#usernameTip').html('<span class="error">網絡請求失敗</span>');
            });
        });
    });
    </script>
</body>
</html>

後端驗證 check_user.php

<?php
header('Content-Type: application/json; charset=utf-8');

// 模擬數據庫查詢,實際應用連接 PDO/MySQLi
$existingUsers = ['admin', 'test', 'demo', 'root', 'user'];

$username = trim($_POST['username'] ?? '');
$response = ['exists' => false, 'msg' => ''];

if ($username === '') {
    $response['msg'] = '用戶名不能為空';
} elseif (in_array(strtolower($username), $existingUsers)) {
    $response['exists'] = true;
    $response['msg'] = '用戶名已被註冊';
} else {
    $response['msg'] = '用戶名可用';
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);

關鍵知識點總結

概念說明
$(document).ready(fn) / $(fn)DOM 就緒執行,比 window.onload 更早(不等圖片),可多次調用。
$.post(url, data, callback)POST 方式 AJAX,data 可為對象自動序列化,callback 接收響應。
.blur()失去焦點事件,適合表單字段驗證。
JSON 交互前後端統一約定 JSON 格式,header('Content-Type: application/json') + json_encode。
防抖優化高頻輸入建議加 setTimeout / _.debounce 減少請求。
CSRF 保護生產環境 AJAX 需攜帶 Token,後端驗證。

進階:防抖版本

let timer = null;
$('#username').on('input', function() {
    clearTimeout(timer);
    const $this = $(this);
    timer = setTimeout(() => {
        const username = $this.val().trim();
        if (!username) return;
        $.post('check_user.php', {username}, function(res) {
            // 同樣處理響應
        });
    }, 300); // 300ms 靜默後發請求
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved