使用php跳转界面和AJAX都可实现登录界面的跳转的登录失败对的提醒。但是,php跳转的方式
需要额外加载其他界面,用户体验差。AJAX可实现当前页面只刷新需要的数据,不对当前网页进行
重新加载或者是跳转。
做一个简单的登录界面:
<div id="">用户名 :<input type="text" name="" id="uid" value="" /></div><div id="">密 码 :<input type="text" name="" id="pwd" value="" /></div><div id=""><input type="button" name="" id="denglu" value="登录" /></div>
然后是js代码,使用jq比较简单,所以要先引入jq文件包。
其次获取用户名和密码的值:
var uid = $("#uid").val();var pwd = $("#pwd").val();
设置好之后就可以进行AJAX的设置了:
$.ajax({type: "post",url: "dengluchuli.php",data: {u: uid,p: pwd},dataType: "TEXT",success: function(r) { //r为返回值if(r.trim() == "y") { //y为 url跳转网页中传回的值。window.location.href = "跳转界面";} else {alert("用户名或密码错误");}}});
dengluchuli.php:
<?phpinclude("AJAXLOGIN.class.php");$dd = new LoGin($_POST["u"],$_POST["p"]);$ae = $dd::logi("login","username","password","name"); //分别是数据库中的 表名,表中的用户名,密码,姓名(数据从数据库中导入)?>
这里我引入了一个登录类(AJAXLOGIN.class.php),是为了以后方便使用:
<?phpclass DBDA{public $host="localhost";public $uid = "root";public $pwd = "";public $dbname = "12345";//成员方法public function Query($sql,$type=1){$db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);$r = $db->query($sql);if($type==1){return $r->fetch_all();}else{return $r;}}}class LoGin{ public static $uid ;public static $pwd ;function __construct($x,$y) { self::$uid = $x; self::$pwd = $y; }static function logi ($table,$username,$password,$name){$db = new DBDA();$nnn = self::$uid;$sql = " select $name,$password from $table where $username='$nnn '" ;$at = $db->Query($sql);$p = self::$pwd;if(!empty($p) && $p==$at[0][1]){$_SESSION["uid"]= $at[0][0];echo "y";}else{echo "n";}}}?>
登录界面完整代码:
<!doctype html><html lang="en"><head><meta charset="UTF-8" /><title>Document</title><script src="../jquery-1.11.2.min.js" type="text/javascript" charset="utf-8"></script></head><body><div id="">用户名 :<input type="text" name="" id="uid" value="" /></div><div id="">密 码 :<input type="text" name="" id="pwd" value="" /></div><div id=""><input type="button" name="" id="denglu" value="登录" /></div></body><script type="text/javascript">$("#denglu").click(function() {var uid = $("#uid").val();var pwd = $("#pwd").val();$.ajax({type: "post",url: "dengluchuli.php",data: {u: uid,p: pwd},dataType: "TEXT",success: function(r) {if(r.trim() == "y") {window.location.href = "ppp.php";} else {alert("用户名或密码错误");}}});})</script></html>