PHP+Ajax无刷新登录与退出
程序员文章站
2024-01-15 08:37:22
...
本文使用Ajax无刷新登录和退出,从而提升了用户体验。
无刷新登录演示效果: http://www.sucaihuo.com/js/54.html
无刷新登录演示效果: http://www.sucaihuo.com/js/54.html
$(".btn").live('click',function(){
var user = $("#user").val();
var pass = $("#pass").val();
if(user==""){
$('').html("用户名不能为空!").appendTo('.sub').fadeOut(2000);
$("#user").focus();
return false;
}
if(pass==""){
$('').html("密码不能为空!").appendTo('.sub').fadeOut(2000);
$("#pass").focus();
return false;
}
$.ajax({
type: "POST",
url: "ajax.php?action=login",
dataType: "json",
data: {"user":user,"pass":pass},
beforeSend: function(){
$('').addClass("loading").html("正在登录...").css("color","#999")
.appendTo('.sub');
},
success: function(json){
if(json.success==1){
$("#login_form").remove();
var div = "";
$("#login").append(div);
}else{
$("#msg").remove();
$('').html(json.msg).css("color","#999").appendTo('.sub')
.fadeOut(2000);
return false;
}
}
});
});
程序代码:session_start();
require_once ('connect.php');
$action = $_GET['action'];
if ($action == 'login') { //登录
$user = stripslashes(trim($_POST['user']));
$pass = stripslashes(trim($_POST['pass']));
if (empty ($user)) {
echo '用户名不能为空';
exit;
}
if (empty ($pass)) {
echo '密码不能为空';
exit;
}
$md5pass = md5($pass); //密码使用md5加密
$query = mysql_query("select * from user where username='$user'");
$us = is_array($row = mysql_fetch_array($query));
$ps = $us ? $md5pass == $row['password'] : FALSE;
if ($ps) {
$counts = $row['login_counts'] + 1;
$_SESSION['user'] = $row['username'];
$_SESSION['login_time'] = $row['login_time'];
$_SESSION['login_counts'] = $counts;
$ip = get_client_ip(); //获取登录IP
$logintime = mktime();
$rs = mysql_query("update user set login_time='$logintime',login_ip='$ip',
login_counts='$counts'");
if ($rs) {
$arr['success'] = 1;
$arr['msg'] = '登录成功!';
$arr['user'] = $_SESSION['user'];
$arr['login_time'] = date('Y-m-d H:i:s',$_SESSION['login_time']);
$arr['login_counts'] = $_SESSION['login_counts'];
} else {
$arr['success'] = 0;
$arr['msg'] = '登录失败';
}
} else {
$arr['success'] = 0;
$arr['msg'] = '用户名或密码错误!';
}
echo json_encode($arr); //输出json数据
}
elseif ($action == 'logout') { //退出
unset($_SESSION);
session_destroy();
echo '1';
}
本文转自素材火:http://www.sucaihuo.com/js AD:真正免费,域名+虚机+企业邮箱=0元