上一篇部落格介紹了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">×</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();}
這樣基本完成了登入驗證,我們在添加一些網站響應,大部分代碼我已經在我的另一篇部落格介紹過了
BootstrapCSS與Bootstrap表單互動修改樣式的JS——筆記整理
/* 修改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'>×</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