现在很多网站都采用了jQuery弹窗功能,看起来是非常的酷炫,在代码狗以前的文章中也说过ajax与服务器的异步通讯,今天就结合两者,做一个弹窗异步登陆效果。
首先使用HTML写一个登陆界面,如下图:
代码很简单,HTML、css、js所有代码都贴出来。
复制
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>代码狗</title>
<link href="css/main.css" rel="stylesheet"/>
<script src="js/jquery-3.2.0.min.js"></script>
<script src="js/layer/layer.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div id="header">
<div id="daohang">
<div><a href="javascript:;" onclick="showloginbox()" >登陆</a></div>
<div><a href="javascript:;" >注册</a></div>
</div>
</div>
<div id="loginbox">
<div class="login-item"><input type="text" id="username"/></div>
<div class="login-item"><input type="password" id="password"/></div>
<div class="login-item"><a href="javascript:;" onclick="login()"/>登陆</div>
</div>
</body>
</html>复制
*{
padding: 0px;
margin: 0px;
font-family:"微软雅黑";
}
#header{
width: 100%;
height: 40px;
background-color: #fff;
}
a{
text-decoration: none;
}
#daohang{
width: 800px;
height: 40px;
background-color: #555555;
margin: 0px auto;
}
#daohang div{
float: right;
line-height: 40px;
margin-left: 10px;
display: block;
}
#daohang div a{
color: #fff;
}
.login-item input{
width: 350px;
height: 40px;
}
.login-item a{
width: 355px;
height: 50px;
background-color:#ff00ef;
display: block;
text-align: center;
line-height: 50px;
color: #fff;
font-size: 20px;
}
.login-item{
margin-top: 15px;
margin-left: 20px;
}
#loginbox{
display: none;
}复制
function showloginbox(){
layer.open({
type:1,
title:"登陆",
area:["395px","300px"],
content:$("#loginbox")
});
}
function login(){
var username= $.trim($("#username").val());
var pwd= $.trim($("#password").val());
if(username==""||pwd==""){
layer.alert("用户名或密码不能为空",{
title:"提示",
icon:5
});
}
else{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
layer.alert(xmlhttp.responseText,{
title:"提示",
icon:6,
time:1000
});
}
}
xmlhttp.open("POST","http://127.0.0.1/test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username="+username+"&pwd="+pwd);
}
}弹窗使用了layer的弹窗效果,使用简单漂亮。喜欢的朋友可以去百度进他的官网学习学习。
测试时使用的本地服务器通讯,服务端PHP文件很简单,直接使用PHP输出post数据。
注意:ajax在本地环境调试时,不要使用Chrome内核浏览器,Chrome内核的流量器会拦截本地的ajax请求,使用IE内核即可,或者上传到服务器测试。








评论 (1)