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