Ajax+php驗證登錄用戶名是否存在

若是用戶名存在,則無提示
若是不存在,則提示而且禁用提交按鈕php

clipboard.png

login.htmlhtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用戶登陸</title>
</head>
<body>
<div align="center">
    <h3>用戶登陸</h3>
    <form action="check.php" method="post">
        <p>賬號: <input type="text" name="name" id="name"></p>
        <span id="warning" style="color:red"></span>
        <p>密碼: <input type="password" name="password" id="password"></p>
        <p><input type="submit" id="submit" value="提交"></p>
        <p id="tips"></p>
    </form>
</div>
</body>
<script>
    var user = document.getElementById('name');  //獲取用戶控件
    user.onblur = function () {  //當用戶離開當前文本框的時行驗證
        //1.建立Ajax對象
        var xhr = new XMLHttpRequest();
        //2.建立請求事件的監聽
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (xhr.responseText == 0) {  //當前用戶不存在
                    var warning = document.getElementById('warning');
                    warning.innerHTML = '新用戶,請先註冊再登陸~~';
                    document.getElementById('submit').disabled = true;
                }
            }
        }

        //3.初始化一個url請求
        var user = document.getElementById('name').value;
        var password = document.getElementById('password').value;
        var data = 'name='+user+'&password='+password; //生成post請求數據
        var url = 'check.php';
        xhr.open('post',url,true); //請求類型爲post,交互方式爲異步

        //4.設置請求頭
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

        //5.發送url請求,須要傳入參數
        xhr.send(data);

        var submit = document.getElementById('submit');
        submit.onclick = function () {
            var tips = document.getElementById('tips');
            tips.innerHTML = '驗證經過,正在跳轉中~~';
            return false;
        }
    }
</script>
</html>

check.php數據庫

<?php
$userList = ['peter', 'jack', 'mike'];  //已註冊用戶列表
$user = isset($_POST['name']) ? $_POST['name'] : '';
echo in_array($user, $userList) ? 1 : 0;  //若是用戶名不在列表中返回0,不然返回1

本次登錄驗證沒有用數據庫進行驗證,而是用數組,用在項目上能夠換成數據庫。數組

相關文章
相關標籤/搜索