PHP如何通过AJAX方式实现登录功能
程序员文章站
2022-05-22 09:38:02
本文实例讲述了ajax+php+mysql登陆示例。分享给大家供大家参考。具体如下:
运行效果截图如下:
具体代码如下:
1 login.php
登录界面中,j...
本文实例讲述了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 style="background-color:#2a3f55; height:80px;"> </div> <div style="min-height:500px;"> <div class="left"> <div style="margin:120px auto auto auto; height:300px; text-align:left"> <div style="font-size:26px;color:#2a3f55; text-align:center;">ajax php demo system <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;"/> </div> <br/> <hr style="border:dashed thin #2a3f55;width:70%; text-align:center;"/> <div style="font-size:13px;color:#999999; margin:20px auto 0 auto; padding-left:200px;"> author:<a href="#" onmousemove="showtool();" onmouseout="hidetool();">wangming</a> </div> <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">datetime:2009-9-1</div> <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">version:1.0.0</div> <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">email:wangmingemail@163.com </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;" style=" vertical-align:bottom;"/> </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 style="background-color:#2a3f55; height:60px; margin:auto 0 0 0; clear:both; text-align:center; line-height:60px; color:#ffffff;font-size:12px;"> ©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方式实现登录功能,希望对大家的学习有所帮助。
下一篇: 西兰花减肥吗