简单的ajax登陆验证

前端之家收集整理的这篇文章主要介绍了简单的ajax登陆验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。





1.login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login</title>
<script type="text/javascript">
function createAjax() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
};
function checkLogin() {
var loginName = document.getElementById("username").value;
var xmlHttp = createAjax();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var data = xmlHttp.responseText;
alert(document.getElementById("suggest"));
document.getElementById("suggest").innerHTML = data;
}
}
};
xmlHttp.open("post","checkLogin",true);
xmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttp.send("loginName=" + loginName);
};
</script>
</head>
<body>
<form action="">
用户名:<input type="text" name="username" id="username"
onblur="checkLogin()" /><span id="suggest"></span><br>
密&nbsp;&nbsp;&nbsp;码:<input type="password" name="password"
id="password" />
</form>
</body>
</html>


2.CheckLogin

package edu.cslg.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "checkLogin",urlPatterns = { "/checkLogin" }) public class CheckLogin extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { System.out.println(1); String loginName = request.getParameter("loginName"); System.out.println(loginName); PrintWriter out = response.getWriter(); if (loginName.equals("1")) { out.print("ok"); } else { out.print("error"); } } }

猜你在找的Ajax相关文章