废话不多说,先上效果图:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0b22298e86c46d89e4817d633be71cb3.gif)
先上主要的jQuery代码
<script type="text/javascript">
$(function(){
$("#name").blur(function () {
var name1 = $("#name").val();
var regName = /^[a-z0-9_-]{3,16}$/;
if(regName.test(name1)){
$("#name").css("border-color","green");
}else {
$("#name").css("border-color","red");
}
})
$("#pwd").blur(function () {
var pwd1 = $("#pwd").val();
var regPwd = /^[a-z0-9_-]{3,16}$/;
if(regPwd.test(pwd1)){
$("#pwd").css("border-color","green");
}else {
$("#pwd").css("border-color","red");
}
})
$(":button").on("click",function(){
$.ajax({
type:"post",
url:"test",
data:{
name:$("#name").val(),
pwd:$("#pwd").val()
},
dataType:"text",
success:function(data){
if(data =="ok"){
window.location.href="loginSuccess.jsp";
}else{
alert("登录失败");
}
}
});
})
})
</script>
</html>
css+HTML代码如下
<style type="text/css">
body{
margin: 0;
padding: 0;
}
#bg{
width: 100%;
height: 800px;
background-image: url(image/andrei-bazanov-loshadi-trava-oblaka-solntse-andrey-bazanov-h.jpg) ;
}
#item input{
margin-top: 10px;
width: 200px;
height: 30px;
}
#item{
margin: 0 auto;
margin-top: 350px;
margin-right: 200px;
float: right;
font-size: 16px;
font-family: "bookshelf symbol 7";
}
</style>
<body>
<div id="bg">
<div id="item">
名字:<input type="text" name="name" id="name" /><br />
密码:<input type="password" name="pwd" id="pwd" /><br />
<input type="button" value="登录" />
</div>
<div id="show"></div>
</div>
</body>
servlet代码
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = "admin";
String pwd = "123456";
String formName = request.getParameter("name");
String formPwd = request.getParameter("pwd");
System.out.print(formName+":"+formPwd);
if(name.equals(formName) && pwd.equals(formPwd)){
out.print("ok");
}else{
out.print("error");
}
out.flush();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}