之前一直都是用封装好的Ajax,所以一直很好奇它是如何使用和实现的。这里正好就进行一下学习,下面是Ajax的一个时间图。
设置触发条件
这里模拟一个使用场景,就是在用户登陆时,异步的对用户名以及密码进行验证。所以使用onBlur()触发,onBlur函数在输入框焦点遗失时,就会触发。
<form name="loginForm">
<table>
<tr>
<td>用戶名:<input type="text" name="username" onBlur="checkUsername()"></td>
</tr>
<tr>
<td><div id="usernameDiv"></div></td>
</tr>
<tr>
<td>密 码:<input type="password" name="password" onBlur="checkPassword()"></td>
</tr>
<tr>
<td><div id="passwordDiv"></div></td>
</tr>
</table>
</form>
创建Ajax的对象
由于Ajax并不是一个统一的标准,因此各个浏览器有自己的创建方式,因此在创建时,需要进行浏览器的验证,使用如下的验证方法即可。
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
open() onreadystatechante() send()
3.1 open(),这个函数有三个参数,第一个是http的发送方式,常见的有GET和POST,我们这里使用GET,来传送参数;第二个参数是一个url,这个url第一个作用是与后台的servlet进行匹配,第二个作用是传送前台的数据到后台;第三个参数是个bool值,如果为true标识用异步的方式发送请求。
req.open("GET",url+"?username="+document.loginForm.username.value,true);
3.2 onreadystatechange 指定回调函数,当数据返回时,使用该函数进行处理。我们的处理函数是自己定义的usernameCallback
req.onreadystatechange = usernameCallback;
3.3 send函数用来发送创建好的请求。由于前面的参数已经添加到url后面,因此这里直接使用null作为参数就行了。
req.send(null);
自己定义的usernameCallback函数,用于把返回的字符串使用DOM方式写入指定的div中。
在函数返回时,可以使用之前创建好的req对象,调用它的readystate 以及 status属性,4表示XMLHttpRequest对象响应正常结束。200表示HTTP请求获得正确的响应。
只有这两个条件都满足,才表明异步请求请求成功。
function usernameCallback(){
if(req.readyState == 4){
if(req.status == 200){
var str = req.responseText;
if(str.split("!")[0] == "Success"){
document.getElementById("usernameDiv").className = "black";
}else{
document.getElementById("usernameDiv").className = "red";
}
document.getElementById("usernameDiv").innerHTML = str;
}else{
alert("username failed!");
}
}else{ }
}
通过url与后台的servlet关联
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>checkUsername</servlet-name>
<servlet-class>usernameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkUsername</servlet-name>
<url-pattern>/checkUsername</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>checkPassword</servlet-name>
<servlet-class>passwordServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkPassword</servlet-name>
<url-pattern>/checkPassword</url-pattern>
</servlet-mapping>
</web-app>
简单反馈
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache"); String username = request.getParameter("username");
// System.out.println("username"+username);
String str = ""; if("xingoo".equals(username)){
str += "Success!" + username;
}else{
str += "failed!" + username;
} response.getWriter().write(str);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
另一个验证的servlet采用同样的方式,这里就不再赘述了。下面会贴出所有的代码。
源码暴露
Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.red {
color:red;
font-size: 20;
}
.black {
color: black;
font-size: 20;
}
</style>
<script language="javascript">
function checkUsername(){
var url = "checkUsername";
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
req.open("GET",url+"?username="+document.loginForm.username.value,true);
req.onreadystatechange = usernameCallback;
req.send(null);
}
}
function checkPassword(){
var url = "checkPassword";
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
req.open("GET",url+"?password="+document.loginForm.password.value,true);
req.onreadystatechange = passwordCallback;
req.send(null);
}
}
function usernameCallback(){
if(req.readyState == 4){
if(req.status == 200){
var str = req.responseText;
if(str.split("!")[0] == "Success"){
document.getElementById("usernameDiv").className = "black";
}else{
document.getElementById("usernameDiv").className = "red";
}
document.getElementById("usernameDiv").innerHTML = str;
}else{
alert("username failed!");
}
}else{ }
}
function passwordCallback(){
if(req.readyState == 4){
if(req.status == 200){
var str = req.responseText;
if(str.split("!")[0] == "Success"){
document.getElementById("passwordDiv").className = "black";
}else{
document.getElementById("passwordDiv").className = "red";
}
document.getElementById("passwordDiv").innerHTML = str;
}else{
alert("password failed!");
}
}else{ }
}
</script>
</head>
<body>
<form name="loginForm">
<table>
<tr>
<td>用戶名:<input type="text" name="username" onBlur="checkUsername()"></td>
</tr>
<tr>
<td><div id="usernameDiv"></div></td>
</tr>
<tr>
<td>密 码:<input type="password" name="password" onBlur="checkPassword()"></td>
</tr>
<tr>
<td><div id="passwordDiv"></div></td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>checkUsername</servlet-name>
<servlet-class>usernameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkUsername</servlet-name>
<url-pattern>/checkUsername</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>checkPassword</servlet-name>
<servlet-class>passwordServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkPassword</servlet-name>
<url-pattern>/checkPassword</url-pattern>
</servlet-mapping>
</web-app>
usernameServlet.java
import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class usernameServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache"); String username = request.getParameter("username");
// System.out.println("username"+username);
String str = ""; if("xingoo".equals(username)){
str += "Success!" + username;
}else{
str += "failed!" + username;
} response.getWriter().write(str);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
}
passwordServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class passwordServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache"); String password = request.getParameter("password");
// System.out.println("password"+password);
String str = ""; if("123".equals(password)){
str += "Success!" + password;
}else{
str += "failed!" + password;
} response.getWriter().write(str);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
}
运行效果
这里直接判断返回状态,进行样式的改变
成功时的效果!
失败时的效果!