程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP如何通過AJAX方式實現登錄功能,phpajax方式登錄

PHP如何通過AJAX方式實現登錄功能,phpajax方式登錄

編輯:關於PHP編程

PHP如何通過AJAX方式實現登錄功能,phpajax方式登錄


本文實例講述了Ajax+PHP+MySQL登陸示例。分享給大家供大家參考。具體如下:
運行效果截圖如下:

具體代碼如下:

1 login.php
登錄界面中,javascript腳本用ajax方式異步請求dologin.php,dologin.php負責用戶信息驗證(包括驗證碼,php生成驗證碼可以自行搜索).登錄界面的代碼如下:

<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 <title>login</title>
 <link rel="stylesheet" type="text/css" href="CSS/login.css" />
 <script src="JS/ajaxhelper.js" type="text/javascript"></script>
 <script src="JS/jquery-1.3.2.min.js" type="text/javascript"></script>
 <script type="text/javascript">
  function chkForm() {
   if (m$('username').value == "") {

    alert('用戶名不能為空.');
    m$('username').focus();
    return false;

   }
   if (m$('password').value == "") {

    alert('密碼不能為空.');
    m$('password').focus();
    return false;

   }
   if (m$('password').value != "" && m$('username').value != "") {

    var xmlhttp = createRequest();
    if (xmlhttp) {
     m$('loading').innerHTML = "<font color='red'>loading...</font>";
     var username = m$('username').value;
     var pwd = m$('password').value;
     var code = m$('txtCode').value;
     var url = "dologin.php";
     xmlhttp.open("POST", url, true);
     xmlhttp.onreadystatechange = ValidateResult;
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlhttp.send("username=" + escape(username) + "&password=" + escape(pwd) + "&code=" + escape(code));

    } else {
     alert('xmlHttp創建失敗.');

    }

    function ValidateResult() {
     if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
       if (xmlhttp.responseText != "") {

        //window.alert(xmlhttp.responseText);
        var obj = eval("(" + xmlhttp.responseText + ")");
        if (obj.result == true) {
         alert("提示:" + obj.info);
         window.location = 'index.php';

        } else {
         alert("錯誤:" + obj.info);

        }
       } else {
        window.alert("從服務器獲取失敗");

        window.location.reload();
       }
       m$('loading').innerHTML = "";
      }
     }

    }


   }

  }

  function m$(id) {
   return document.getElementById(id);
  }

  function changeCode() {
   var xmlhttp = createRequest();
   if (xmlhttp) {
    m$('loading').innerHTML = "<font color='red'>loading...</font>";
    var dt = new Date().getTime();
    // alert(dt);
    var url = "function/imagecode.php?dummay" + escape(dt);
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = ValidateResult;
    xmlhttp.send(null);

   } else {
    alert('xmlHttp創建失敗.');

   }

   function ValidateResult() {
    if (xmlhttp.readyState == 4) {
     if (xmlhttp.status == 200) {
      var dt = new Date().getTime();
      var url = "function/imagecode.php?dummay" + escape(dt);
      m$('imgCode').src = "function/imagecode.php?dummay" + escape(dt);
      m$('loading').innerHTML = "";
     }
    }

   }
  }

  function showTool() {
   $('#divToolTip').css("display", "block");
  }

  function hideTool() {
   $('#divToolTip').css("display", "none");
  }
  window.onload = initPage;

  function initPage() {
   $('#divToolTip').css("display", "none");
  }
 </script>
 </head>
 <body>
 <div >
  
 </div>
 <div >
  
  <div class="left">
  
  <div >
   <div >Ajax PHP Demo System
   <img src="Images/appstorm-icon.png" alt="appcation storm image" />
   </div>
   <br/>
   <hr />
   <div >
   Author:<a href="#" onmousemove="showTool();" onmouseout="hideTool();">wangming</a>
   </div>
   <div >DateTime:2009-9-1</div>
   <div >Version:1.0.0</div>
   <div >Email:[email protected]     </div>
   <div id="divToolTip">
   <img src="Images/ming.jpg" height="86px;"/>
   <span class="authordes">
    <br/>
    姓名:wangming<br/>
    電商06-2<br/>
   </span>
   
   </div>
   
  </div>
  
  </div>
  
  <div class="right">
  
  <form>
   <br/>
   <table class="flogin">
   <tr>
    <td>用戶名:</td>
    <td><input type="text" name="username" id="username"/></td>
    <td></td>
   </tr>
   <tr>
    <td>密   碼:</td>
    <td><input type="password" name="password" id="password" /></td>
    <td></td>
   </tr>
   <tr>
    <td>驗證碼:</td>
    <td>
    <input type="text" name="txtCode" id="txtCode" size="12" /> 
    <img src="function/imagecode.php" id="imgCode" alt="image code" height="22px;" />
    </td>
    <td><input type="button" class="btnrefresh" onclick="changeCode();" /></td>
   </tr>
   <tr>
    <td></td>
    <td><input type="button" class="btnlogin" onclick="chkForm();" /></td>
    <td></td>
   </tr>
   <tr>
    <td></td>
    <td><span id="loading"></span></td>
    <td><span id="code"></span></td>
   </tr>
   
   </table>
  </form>
  </div>
  
 </div>
 <div >
  ©Copyright 2015.
 </div>
 </body>
</html>

2 ajaxhelper.js

function createRequest() {
 try {
  request = new XMLHttpRequest();
 } catch (tryMS) {
  try {
   request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (otherMS) {
   try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
    request = null;
   }
  }
 }
 return request;
}

function getActivatedObject(e) {
 var obj;
 if (!e) {
  // early version of IE
  obj = window.event.srcElement;
 } else if (e.srcElement) {
  // IE 7 or later
  obj = e.srcElement;
 } else {
  // DOM Level 2 browser
  obj = e.target;
 }
 return obj;
}

function addEventHandler(obj, eventName, handler) {
 if (document.attachEvent) {
  obj.attachEvent("on" + eventName, handler);
 } else if (document.addEventListener) {
  obj.addEventListener(eventName, handler, false);
 }
}

3 dologin.php

<?php
 session_start();
 header("Content-type:text/html;charset=gb2312");//防止返回的中文亂碼
 $name=$_POST['username'];
 $pwd=$_POST['password'];
 $imagecode=$_POST['code'];
 if(strtoupper($imagecode)==$_SESSION["code"])
 {
  include("conn/conn.php");
  $sql="select studentName,studentPwd from tbstudent where studentId='".$name."'";
  $result=mysql_query($sql,$conn);
  if($row=mysql_fetch_assoc($result))
  {
   if($pwd==$row['studentPwd'])
   {
   $_SESSION['username']=$row['studentName'];
   //echo "{'result':true,'info':'登陸成功!','code':'".$_SESSION["code"]."'}";
   echo "{'result':true,'info':'登陸成功!'}";
   
   }
   else
   {
   echo "{'result':false,'info':'密碼錯誤!'}";
   }
  }
  else
  {
   echo "{'result':false,'info':'該用戶不存在!'}";
  }
 }
 else
 {
  echo "{'result':false,'info':'驗證碼錯誤!'}";
 }
?>

4 conn.php

<?php
 $conn=$mysql_connect("localhost","root", "");
 mysql_select_db("bbs",$conn);
 mysql_query("SET NAMES GB2312");
 ?>
 5
 <?php
class Users {
 function Users() {
 }
 function checkLogin($username, $userpwd) {
  try {
   mysql_connect("localhost", "root", "123");
   mysql_select_db("studentdb");
   mysql_query("SET NAMES GB2312");
   $sql = "select userid from tbuser where username='$username' and userpwd='" . md5(trim($userpwd)) . "'";
   $result = mysql_query($sql);
   if ($result) {
    $arr = mysql_fetch_row($result);
    $uid = $arr[0];
    if ($uid != "") {
     return "true|$uid login ok.$sql";
     mysql_close();
    } else {
     return "false|login failed!$sql";
     mysql_close();
    }
   } else {
    return "false|$result link db failed!";
    mysql_close();
   }
  }
  catch(Exception $ex) {
   return "false|$ex";
   mysql_close();
  }
 }
 function AddUser($name, $pwd) {
  try {
   mysql_connect("localhost", "root", "123");
   mysql_select_db("studentdb");
   mysql_query("set names gb2312");
   $sql0 = mysql_query("select userid from tbuser where username='$name'");
   $info0 = mysql_fetch_array($sql0);
   $userid = $info0[0];
   if ($info0 != false) {
    return "false | $name is exisis.(id:$userid)";
   }
   $pwd = md5(trim($pwd));
   $query = mysql_query("insert into tbuser(username,userpwd)values('$name','$pwd')");
   $error = mysql_errno();
   if ($query) {
    return "true | add ok";
   } else {
    return "false | $error";
   }
  }
  catch(Exception $ex) {
   return "false | $ex";
  }
 }
 function DeleteUser($name) {
  mysql_connect("localhost", "root", "123");
  mysql_select_db("studentdb");
  mysql_query("set names gb2312");
  $name = trim($name);
  $sql0 = mysql_query("select userid from tbuser where username='$name'");
  $info0 = mysql_fetch_array($sql0);
  if ($info0 != false) {
   if (mysql_query("delete from tbuser where username='$name'")) {
    return "true | delete ok.(id:" . $info0[0] . ")";
   } else {
    return "false | 刪除失敗";
   }
  } else {
   return "false | 刪除失敗 $name 不存在";
  }
 }
 function UpdateUser($id, $name, $pwd) {
  if (is_numeric(intval(trim($id)))) {
   if ($id && $name && $pwd) {
    mysql_connect("localhost", "root", "123");
    mysql_select_db("studentdb");
    mysql_query("set names gb2312");
    $pwd = md5(trim($pwd));
    $isexists = mysql_query("select * from tbuser where userid='$id'");
    if (mysql_fetch_array($isexists)) {
     $sql0 = mysql_query("update tbuser set username='$name',userpwd='$pwd' where userid= $id");
     if ($sql0) {
      return "ture | update ok";
     } else {
      return "false | 更新失敗";
     }
    } else {
     return "false | usrid=$id not exists.";
    }
   } else {
    return "false |id=$id name=$name and pwd=$pwd .At least one of them is null.";
   }
  } else {
   return "false | $id is not type of int.";
  }
 }
}
?>

與登錄無關,只為了記錄一下PHP如何在數據庫MYSQL上實現CURD操作.

以上就是告訴了大家PHP如何通過AJAX方式實現登錄功能,希望對大家的學習有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved