当前位置:首页 > PHP教程 > php应用 > 列表

PHP如何通过AJAX方式实现登录功能

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-27 13:06:46 浏览: 评论:0 

PHP是一门很好的语言,可以很方便的开发web应用程序,下面介绍一下Ajax+PHP+MySQL登陆示例,感兴趣的小伙伴们可以参考一下,本文实例讲述了Ajax+PHP+MySQL登陆示例,分享给大家供大家参考,具体如下:

1 login.php

登录界面中,javascript脚本用ajax方式异步请求dologin.php,dologin.php负责用户信息验证(包括验证码,php生成验证码可以自行搜索).登录界面的代码如下:

  1. <?php session_start();?> 
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
  3. <html xmlns="http://www.w3.org/1999/xhtml"
  4.  <head> 
  5.  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  6.  <title>login</title> 
  7.  <link rel="stylesheet" type="text/css" href="CSS/login.css" /> 
  8.  <script src="JS/ajaxhelper.js" type="text/javascript"></script> 
  9.  <script src="JS/jquery-1.3.2.min.js" type="text/javascript"></script> 
  10.  <script type="text/javascript"
  11.   function chkForm() { 
  12.    if (m$('username').value == "") { 
  13.  
  14.     alert('用户名不能为空.'); 
  15.     m$('username').focus(); 
  16.     return false; 
  17.  
  18.    } 
  19.    if (m$('password').value == "") { 
  20.  
  21.     alert('密码不能为空.'); 
  22.     m$('password').focus(); 
  23.     return false; 
  24.  
  25.    } 
  26.    if (m$('password').value != "" && m$('username').value != "") { 
  27.  
  28.     var xmlhttp = createRequest(); 
  29.     if (xmlhttp) { 
  30.      m$('loading').innerHTML = "<font color='red'>loading...</font>"
  31.      var username = m$('username').value; 
  32.      var pwd = m$('password').value; 
  33.      var code = m$('txtCode').value; 
  34.      var url = "dologin.php"
  35.      xmlhttp.open("POST", url, true); 
  36.      xmlhttp.onreadystatechange = ValidateResult; 
  37.      xmlhttp.setRequestHeader("Content-Type""application/x-www-form-urlencoded"); 
  38.      xmlhttp.send("username=" + escape(username) + "&password=" + escape(pwd) + "&code=" + escape(code)); 
  39.  
  40.     } else { 
  41.      alert('xmlHttp创建失败.'); 
  42.  
  43.     } 
  44.  
  45.     function ValidateResult() { 
  46.      if (xmlhttp.readyState == 4) { 
  47.       if (xmlhttp.status == 200) { 
  48.        if (xmlhttp.responseText != "") { 
  49.  
  50.         //window.alert(xmlhttp.responseText); 
  51.         var obj = eval("(" + xmlhttp.responseText + ")"); 
  52.         if (obj.result == true) { 
  53.          alert("提示:" + obj.info); 
  54.          window.location = 'index.php'
  55.  
  56.         } else { 
  57.          alert("错误:" + obj.info); 
  58.  
  59.         } 
  60.        } else { 
  61.         window.alert("从服务器获取失败"); 
  62.  
  63.         window.location.reload(); 
  64.        } 
  65.        m$('loading').innerHTML = ""
  66.       } 
  67.      } 
  68.  
  69.     } 
  70.  
  71.  
  72.    } 
  73.  
  74.   } 
  75.  
  76.   function m$(id) { 
  77.    return document.getElementById(id); 
  78.   } 
  79.  
  80.   function changeCode() { 
  81.    var xmlhttp = createRequest(); 
  82.    if (xmlhttp) { 
  83.     m$('loading').innerHTML = "<font color='red'>loading...</font>"
  84.     var dt = new Date().getTime(); 
  85.     // alert(dt); 
  86.     var url = "function/imagecode.php?dummay" + escape(dt); 
  87.     xmlhttp.open("GET", url, true); 
  88.     xmlhttp.onreadystatechange = ValidateResult; 
  89.     xmlhttp.send(null); 
  90.  
  91.    } else { 
  92.     alert('xmlHttp创建失败.'); 
  93.  
  94.    } 
  95.  
  96.    function ValidateResult() { 
  97.     if (xmlhttp.readyState == 4) { 
  98.      if (xmlhttp.status == 200) { 
  99.       var dt = new Date().getTime(); 
  100.       var url = "function/imagecode.php?dummay" + escape(dt); 
  101.       m$('imgCode').src = "function/imagecode.php?dummay" + escape(dt); 
  102.       m$('loading').innerHTML = ""
  103.      } 
  104.     } 
  105.  
  106.    } 
  107.   } 
  108.  
  109.   function showTool() { 
  110.    $('#divToolTip').css("display""block"); 
  111.   } 
  112.  
  113.   function hideTool() { 
  114.    $('#divToolTip').css("display""none"); 
  115.   } 
  116.   window.onload = initPage; 
  117.  
  118.   function initPage() { 
  119.    $('#divToolTip').css("display""none"); 
  120.   } 
  121.  </script> 
  122.  </head> 
  123.  <body> 
  124.  <div style="background-color:#2A3F55; height:80px;"
  125.     
  126.  </div> 
  127.  <div style="min-height:500px;"
  128.     
  129.   <div class="left"
  130.     
  131.   <div style="margin:120px auto auto auto; height:300px; text-align:left"
  132.    <div style="font-size:26px;color:#2A3F55; text-align:center;">Ajax PHP Demo System 
  133.    <img src="Images/appstorm-icon.png" alt="appcation storm image" style="position:relative;top:-18px; left:-12px;         vertical-align:middle; text-align:center;font-size:10px; width:65px; height:46px;"/> 
  134.    </div> 
  135.    <br/> 
  136.    <hr style="border:dashed thin #2A3F55;width:70%; text-align:center;"/> 
  137.    <div style="font-size:13px;color:#999999; margin:20px auto 0 auto; padding-left:200px;"
  138.    Author:<a href="#" onmousemove="showTool();" onmouseout="hideTool();">wangming</a> 
  139.    </div> 
  140.    <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">DateTime:2009-9-1</div> 
  141.    <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Version:1.0.0</div> 
  142.    <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Email:wangmingemail@163.com     </div> 
  143.    <div id="divToolTip"
  144.    <img src="Images/ming.jpg" height="86px;"/> 
  145.    <span class="authordes"
  146.     <br/> 
  147.     姓名:wangming<br/> 
  148.     电商06-2<br/> 
  149.    </span> 
  150.      
  151.    </div> 
  152.      
  153.   </div> 
  154.     
  155.   </div> 
  156.     
  157.   <div class="right"
  158.     
  159.   <form> 
  160.    <br/> 
  161.    <table class="flogin"
  162.    <tr> 
  163.     <td>用户名:</td> 
  164.     <td><input type="text" name="username" id="username"/></td> 
  165.     <td></td> 
  166.    </tr> 
  167.    <tr> 
  168.     <td>密&nbsp;&nbsp;&nbsp;码:</td> 
  169.     <td><input type="password" name="password" id="password" /></td> 
  170.     <td></td> 
  171.    </tr> 
  172.    <tr> 
  173.     <td>验证码:</td> 
  174.     <td> 
  175.     <input type="text" name="txtCode" id="txtCode" size="12" />&nbsp; 
  176.     <img src="function/imagecode.php" id="imgCode" alt="image code" height="22px;" style=" vertical-align:bottom;"/> 
  177.     </td> 
  178.     <td><input type="button" class="btnrefresh" onclick="changeCode();" /></td> 
  179.    </tr> 
  180.    <tr> 
  181.     <td></td> 
  182.     <td><input type="button" class="btnlogin" onclick="chkForm();" /></td> 
  183.     <td></td> 
  184.    </tr> 
  185.    <tr> 
  186.     <td></td> 
  187.     <td><span id="loading"></span></td> 
  188.     <td><span id="code"></span></td> 
  189.    </tr> 
  190.      
  191.    </table> 
  192.   </form> 
  193.   </div> 
  194.     
  195.  </div> 
  196.  <div style="background-color:#2A3F55; height:60px; margin:auto 0 0 0; clear:both; text-align:center; line-height:60px; color:#FFFFFF;font-size:12px;"
  197.   &copy;Copyright 2015. 
  198.  </div> 
  199.  </body> 
  200. </html> 

2 ajaxhelper.js

  1. function createRequest() { 
  2.  try { 
  3.   request = new XMLHttpRequest(); 
  4.  } catch (tryMS) { 
  5.   try { 
  6.    request = new ActiveXObject("Msxml2.XMLHTTP"); 
  7.   } catch (otherMS) { 
  8.    try { 
  9.     request = new ActiveXObject("Microsoft.XMLHTTP"); 
  10.    } catch (failed) { 
  11.     request = null
  12.    } 
  13.   } 
  14.  } 
  15.  return request; 
  16.  
  17. function getActivatedObject(e) { 
  18.  var obj; 
  19.  if (!e) { 
  20.   // early version of IE 
  21.   obj = window.event.srcElement; 
  22.  } else if (e.srcElement) { 
  23.   // IE 7 or later 
  24.   obj = e.srcElement; 
  25.  } else { 
  26.   // DOM Level 2 browser 
  27.   obj = e.target; 
  28.  } 
  29.  return obj; 
  30.  
  31. function addEventHandler(obj, eventName, handler) { 
  32.  if (document.attachEvent) { 
  33.   obj.attachEvent("on" + eventName, handler); 
  34.  } else if (document.addEventListener) { 
  35.   obj.addEventListener(eventName, handler, false); 
  36.  } 

3 dologin.php

  1. <?php 
  2.  session_start(); 
  3.  header("Content-type:text/html;charset=gb2312");//防止返回的中文乱码 
  4.  $name=$_POST['username']; 
  5.  $pwd=$_POST['password']; 
  6.  $imagecode=$_POST['code']; 
  7.  if(strtoupper($imagecode)==$_SESSION["code"]) 
  8.  { 
  9.   include("conn/conn.php"); 
  10.   $sql="select studentName,studentPwd from tbstudent where studentId='".$name."'"
  11.   $result=mysql_query($sql,$conn); 
  12.   if($row=mysql_fetch_assoc($result)) 
  13.   { 
  14.    if($pwd==$row['studentPwd']) 
  15.    { 
  16.    $_SESSION['username']=$row['studentName']; 
  17.    //echo "{'result':true,'info':'登陆成功!','code':'".$_SESSION["code"]."'}"; 
  18.    echo "{'result':true,'info':'登陆成功!'}"
  19.      
  20.    } 
  21.    else 
  22.    { 
  23.    echo "{'result':false,'info':'密码错误!'}"
  24.    } 
  25.   } 
  26.   else 
  27.   { 
  28.    echo "{'result':false,'info':'该用户不存在!'}"
  29.   } 
  30.  } 
  31.  else 
  32.  { 
  33.   echo "{'result':false,'info':'验证码错误!'}"
  34.  } 
  35. ?> 

4 conn.php

  1. <?php 
  2.  $conn=$mysql_connect("localhost","root"""); 
  3.  mysql_select_db("bbs",$conn); 
  4.  mysql_query("SET NAMES GB2312"); 
  5.  ?> 
  6.  5 
  7.  <?php 
  8. class Users { 
  9.  function Users() { 
  10.  } 
  11.  function checkLogin($username$userpwd) { 
  12.   try { 
  13.    mysql_connect("localhost""root""123"); 
  14.    mysql_select_db("studentdb"); 
  15.    mysql_query("SET NAMES GB2312"); 
  16.    $sql = "select userid from tbuser where username='$username' and userpwd='" . md5(trim($userpwd)) . "'"
  17.    $result = mysql_query($sql); 
  18.    if ($result) { 
  19.     $arr = mysql_fetch_row($result); 
  20.     $uid = $arr[0]; 
  21.     if ($uid != "") { 
  22.      return "true|$uid login ok.$sql"
  23.      mysql_close(); 
  24.     } else { 
  25.      return "false|login failed!$sql"
  26.      mysql_close(); 
  27.     } 
  28.    } else { 
  29.     return "false|$result link db failed!"
  30.     mysql_close(); 
  31.    } 
  32.   } 
  33.   catch(Exception $ex) { 
  34.    return "false|$ex"
  35.    mysql_close(); 
  36.   } 
  37.  } 
  38.  function AddUser($name$pwd) { 
  39.   try { 
  40.    mysql_connect("localhost""root""123"); 
  41.    mysql_select_db("studentdb"); 
  42.    mysql_query("set names gb2312"); 
  43.    $sql0 = mysql_query("select userid from tbuser where username='$name'"); 
  44.    $info0 = mysql_fetch_array($sql0); 
  45.    $userid = $info0[0]; 
  46.    if ($info0 != false) { 
  47.     return "false | $name is exisis.(id:$userid)"
  48.    } 
  49.    $pwd = md5(trim($pwd)); 
  50.    $query = mysql_query("insert into tbuser(username,userpwd)values('$name','$pwd')"); 
  51.    $error = mysql_errno(); 
  52.    if ($query) { 
  53.     return "true | add ok"
  54.    } else { 
  55.     return "false | $error"
  56.    } 
  57.   } 
  58.   catch(Exception $ex) { 
  59.    return "false | $ex"
  60.   } 
  61.  } 
  62.  function DeleteUser($name) { 
  63.   mysql_connect("localhost""root""123"); 
  64.   mysql_select_db("studentdb"); 
  65.   mysql_query("set names gb2312"); 
  66.   $name = trim($name); 
  67.   $sql0 = mysql_query("select userid from tbuser where username='$name'"); 
  68.   $info0 = mysql_fetch_array($sql0); 
  69.   if ($info0 != false) { 
  70.    if (mysql_query("delete from tbuser where username='$name'")) { 
  71.     return "true | delete ok.(id:" . $info0[0] . ")"
  72.    } else { 
  73.     return "false | 删除失败"
  74.    } 
  75.   } else { 
  76.    return "false | 删除失败 $name 不存在"
  77.   } 
  78.  } 
  79.  function UpdateUser($id$name$pwd) { 
  80.   if (is_numeric(intval(trim($id)))) { 
  81.    if ($id && $name && $pwd) { 
  82.     mysql_connect("localhost""root""123"); 
  83.     mysql_select_db("studentdb"); 
  84.     mysql_query("set names gb2312"); 
  85.     $pwd = md5(trim($pwd)); 
  86.     $isexists = mysql_query("select * from tbuser where userid='$id'"); 
  87.     if (mysql_fetch_array($isexists)) { 
  88.      $sql0 = mysql_query("update tbuser set username='$name',userpwd='$pwd' where userid= $id"); 
  89.      if ($sql0) { 
  90.       return "ture | update ok"
  91.      } else { 
  92.       return "false | 更新失败"
  93.      } 
  94.     } else { 
  95.      return "false | usrid=$id not exists."
  96.     } 
  97.    } else { 
  98.     return "false |id=$id name=$name and pwd=$pwd .At least one of them is null."
  99.    } 
  100.   } else { 
  101.    return "false | $id is not type of int."
  102.   } 
  103.  } 
  104. ?> 

与登录无关,只为了记录一下PHP如何在数据库MYSQL上实现CURD操作,以上就是告诉了大家PHP如何通过AJAX方式实现登录功能,希望对大家的学习有所帮助。

Tags: AJAX登录功能

分享到: