1. 程式人生 > >Ajax實現簡單的登入驗證與帳號註冊

Ajax實現簡單的登入驗證與帳號註冊

上一篇部落格介紹了Ajax的GET和POST方法以及上傳檔案的進度條展示,這篇部落格將介紹一個簡單的登入與註冊功能的實現

設計HTML

這裡寫圖片描述

這裡寫圖片描述

這個是即將成為我畢業設計的一個網站,

在導航欄我添加了兩個註冊和登入的按鈕和按下登入按鈕後彈出的登入框,這就構成了一個簡單的登入視窗

程式碼如下: 需引入Bootstrap

<div class="modal fade" id="user_Login" tabindex="-1" role="dialog" aria-labelledby="user_Msg_to" aria-hidden="true">
    <div
class="modal-dialog" id="userLoginBox">
<div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id
="user_Msg_to">
登 錄</h4> </div> <div class="modal-body"> <div id="inputBox" class="text-center"> <p>登入後在雲端儲存你的歌單!</p> <form id="form1"> <p> <div
id="div-email_address" class="input-group">
<span class="input-group-addon"><i class="icon-envelope"></i></span> <input id="user_id" class="form-control" type="text" placeholder="郵箱地址"> </div> </p> <p> <div id="div-password" class="input-group"> <span class="input-group-addon"><i class="icon-key"></i></span> <input id="user_pass" class="form-control" type="password" placeholder="密碼"> </div> </p> <a id="login_to" class="btn btn-block btn-success"> <i class="glyphicon glyphicon-log-in"></i> 登 錄</a> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal"> 關 閉 </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal --> </div>

設計PHP/MySql

這裡主要講述Ajax,關於php以及SQL都直接貼程式碼了:

<?php
$username='root';
$userpass='q12we3';
$host='127.0.0.1';
$database='music';
$conn=new mysqli($host,$username,$userpass,$database);
if(!$conn){
    echo '-1';
    exit;
}

$user_id = trim($_GET['user_id']);
$user_pass = $_GET['user_pass'];

$sql="SELECT * FROM `user` WHERE `user_id` = '".$user_id."' ";
$result=$conn -> query($sql);
$row = $result -> fetch_row();

if($row[0]==""||$user_pass!=$row[1]){
    echo "0";
}else{
    $test = $row[0].'|'.$row[2].'|'.$row[3];
    echo $test;
}

?>
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE `user` (
  `user_id` varchar(16) NOT NULL,
  `user_pass` varchar(16) NOT NULL,
  `user_name` varchar(32) NOT NULL,
  `user_icon` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


INSERT INTO `user` (`user_id`, `user_pass`, `user_name`, `user_icon`) VALUES
('chation99', 'q12we3', '恰西', 'pic/userHead/qx.jpg'),
('admin001', 'wsad2428210', '管理員001', 'pic/userHead/bq2.jpg');


ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

Ajax實現功能

根據我們編寫的PHP程式碼,在我們get資料到php的時候會返回0,或者一段記錄,我們需要通過判斷,如果為0的話代表登入失敗,賬號或密碼錯誤,如果返回一段記錄的話,我們就需要對這段記錄進行分析以”|”為拆分號,將結果拆分為帳號,使用者名稱以及頭像地址,

首先初始化Ajax,為了方便把Ajax繫結為登入按鈕的事件函式,我們需要把它抽象化為一個函式,引數為使用者輸入的帳號和密碼

function ajaxLogin(id,pass,classes){
var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", url, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            //do something..
        }
    };
    xmlhttp.send();
}
}

這裡,我們需要做的重點就是//dosomething這裡!

首先,我們判斷返回值,如果是0就證明登入失敗,做相應的操作,如果為一段記錄,我們就分析該記錄並做相應操作

function ajaxLogin(id,pass,classes){
    var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "pages/loginByNav.php?user_id=" + id + "&user_pass=" + pass, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (xmlhttp.responseText != 0) {
                var textArray = xmlhttp.responseText.split("|");
                //用split()函式分割字串為一個數組
                //next do something..
            }else{
               //do something..
            }
        }
    };
    xmlhttp.send();
}
/* 修改input樣式 */
function loginStyle(idInput, passInput, loginBtn) {
    var classes = "",oldClasses = "";
    var userId = document.getElementById(idInput);
    var userPass = document.getElementById(passInput);
    var login = document.getElementById(loginBtn);
    login.addEventListener("click", function (event) {
        if (userId.value != "" && userPass.value != "") {
            oldClasses = this.getAttribute("class");
            classes = oldClasses + " disabled";
            this.setAttribute("class", classes);
            this.innerHTML = "<i class='icon-refresh icon-spin'></i> 正在登陸...";

            var idU = userId.value;
            var passU = userPass.value;

            event.preventDefault();
            ajaxLogin(idU,passU,oldClasses);

        } else {
            if (userId.value == "") {
                classes = userId.parentNode.getAttribute("class");
                userId.parentNode.setAttribute("class", classes + " has-error");
            }
            if (userPass.value == "") {
                classes = userPass.parentNode.getAttribute("class");
                userPass.parentNode.setAttribute("class", classes + " has-error");
            }
        }
    }, false);
    var focus = function () {
        this.parentNode.setAttribute("class", "input-group");
    };
    userId.addEventListener("focus", focus, false);
    userPass.addEventListener("focus", focus, false);
}

/* Ajax登入 */
function ajaxLogin(id,pass,classes){
    var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "pages/loginByNav.php?user_id=" + id + "&user_pass=" + pass, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (xmlhttp.responseText != 0) {
                var textArray = xmlhttp.responseText.split("|");
                document.getElementById("inputBox").innerHTML = "<h3>歡迎回來," + textArray[1] + "</h3><img class='img-responsive img-circle' src='" + textArray[2] + "'>";
                document.getElementById("user_name_nav").innerHTML = " " + textArray[1] + ",歡迎你!";
                document.getElementById("user_img_nav").setAttribute("src", textArray[2]);
                document.getElementById("user_info_nav").style.visibility = "";
                document.getElementById("loginAndReg").style.visibility = "hidden";
                document.getElementById("loginAndReg1").style.visibility = "hidden";
            }else{
                var login = document.getElementById("login_to");
                login.setAttribute("class",classes);
                login.innerHTML = "<i class='glyphicon glyphicon-log-in'></i> 登 錄";
                removeElem("warningTip");
                var tips = "賬號或密碼錯誤!";
                var form = document.getElementById("form1");
                form.insertBefore(alertBox(tips,"warning"),form.childNodes[0]);
            }
        }
    };
    xmlhttp.send();
}

/* 新建提示框innerHTML */
function alertBox (tip,color){
    var box = document.createElement("div");
    box.setAttribute("id","warningTip");
    box.setAttribute("class","alert alert-"+color+" alert-dismissible");
    box.setAttribute("role","alert");
    box.innerHTML = "<button type='button' class='close' data-dismiss='alert' aria-label='Close'><spanaria-hidden='true'>&times;</span></button>"+tip;
    return box;
}

效果如下~

這裡寫圖片描述

這裡寫圖片描述

註冊

註冊與登入大同小異,這裡我多介紹一些其他功能的實現,

首先是php程式碼

<?php
$username='root';
$userpass='q12we3';
$host='127.0.0.1';
$database='music';
$conn=new mysqli($host,$username,$userpass,$database);
if(!$conn){
    echo '-1';
    exit;
}

$user_name = trim($_GET['user_name']);
$user_id = trim($_GET['email_address']);
$user_pass = $_GET['password'];

$sql = "INSERT INTO `user` (`user_id`, `user_pass`, `user_name`, `user_icon`) VALUES ('$user_id', '$user_pass', '$user_name', 'pic/default.jpg')";

if ($conn->query($sql) === TRUE) {
    echo "1";
} else {
    echo "0";
}

$conn->close();

?>

註冊成功返回1,失敗返回0; 註冊頁面如下:

這裡寫圖片描述

<body>
<div id="head-div">
    <a href="../index.html"><span class="icon-music" style="font-size: xx-large"></span></a>
</div>
<h4>填寫以下資訊,加入我們</h4>
<div id="form-reg" ng-app="myApp">
    <form id="form1" ng-controller="samePass">
        <p>
        <div id="div-user_name" class="input-group">
                        <span class="input-group-addon" id="sizing-addon2"><i
                                class="glyphicon glyphicon-user"></i></span>
            <input name="user_name" required id="user_name" type="text" class="form-control" placeholder="暱稱">
        </div>
        <span style="visibility: hidden"> </span>
        </p>
        <p>
        <div id="div-email_address" class="input-group">
            <span class="input-group-addon"><i class="icon-envelope"></i></span>
            <input name="email_address" id="email_address" class="form-control" type="text" placeholder="郵箱地址">
        </div>
        <span id="sameUsername" style="color: red;visibility: hidden" >* 帳號已被佔用</span>
        </p>
        <p>
        <div id="div-password" class="input-group">
            <span class="input-group-addon"><i class="icon-key"></i></span>
            <input name="password" id="password" class="form-control" ng-model="pass" type="password" placeholder="設定密碼">
        </div>
        <span style="visibility: hidden"> </span>
        <p>
        <div id="div-password-again" class="input-group">
            <span class="input-group-addon"><i class="icon-key"></i></span>
            <input id="password-again" class="form-control" ng-model="passA" type="password" placeholder="再次輸入密碼">
        </div>
        <span style="color: red" ng-show="pass!=passA">* 保持兩次輸入的密碼一致</span>
        </p>
        <a id="login_to" class="btn btn-block btn-success">
            <i class="glyphicon glyphicon-log-in"></i> 注 冊</a>
    </form>
</div>
<div id="foot-div">

</div>
<script src="../js/pagesJS/regAcc.js"></script>
<script>
    var app = angular.module("myApp",[]);
    app.controller("samePass",function($scope){

    })
</script>
</body>

這裡我引入了AngularJS作為輔助表單驗證的工具,用來繫結兩個密碼框,使使用者保證兩次密碼輸入的一致,這裡不做介紹,在接下來的部落格可能會介紹
javascript程式碼如下:

/* Ajax登入 */
function ajaxLogin(name,id,pass,classes){
    var xmlhttp;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "regAcc.php?user_name=" + name + "&email_address=" + id + "&password=" + pass, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (xmlhttp.responseText == "1") {
                removeElem("form1");
                document.getElementById("form-reg").innerHTML = "<h3>歡迎你," + name + "</h3><img class='img-responsive img-circle' src='../pic/default.jpg'><div id='backTo'><a href='../index.html'>去登入!</a></div>";
            }else{
                var login = document.getElementById("login_to");
                login.setAttribute("class",classes);
                login.innerHTML = "<i class='glyphicon glyphicon-log-in'></i> 注 冊";
                removeElem("warningTip");
                var tips = "發生錯誤,註冊失敗!";
                var form = document.getElementById("form-reg");
                form.insertBefore(alertBox(tips,"warning"),form.childNodes[0]);
            }
        }
    };
    xmlhttp.send();
}

這裡為帳號這一欄繫結一個失去焦點事件:

var user_id = document.getElementById("email_address");
user_id.addEventListener("blur",hasUserName,false);

/* Ajax驗證使用者名稱是否存在 */
function hasUserName(){
    var xmlhttp;
    var tips = document.getElementById("sameUsername");
    var name = document.getElementById("email_address").value;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "hasUserName.php?name="+name, false);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            if (xmlhttp.responseText == "1") {
                tips.style.visibility = "";
                tips.style.color = "green";
                tips.innerHTML = "* 恭喜你,帳號可以使用!";
            }else {
                tips.style.visibility = "";
                tips.style.color = "red";
                tips.innerHTML = "* 賬號已被佔用!"
            }
        }
    };
    xmlhttp.send();
}

好了 ,完成以上的幾個步驟,試試效果

這裡寫圖片描述

這裡寫圖片描述

試著拿剛剛註冊的帳號去登入 !

這裡寫圖片描述