首先介绍一个不错的学习Ajax的中文网站:http://www.w3school.com.cn/ajax/index.asp

AJAX = 异步 JavaScript 和 XML。详细介绍见上面的网址即可;

1:首先介绍一下使用Javascript写的异步验证,然而在实际开发过程中很少用这种的,太过繁琐,但是依旧写一个吧!至少懂其原理哦!

  1.1:第一种方式:先说使用get方法向服务器发送请求的方法吧;

    首先创建一个页面,如register.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=UTF-8">
<title>注册的页面</title>
<script type="text/javascript">
//onblur失去焦点的值 //定义一个变量用于存放XMLHttpRequest对象
var xmlHttp;
function checkIt(){
//获取文本框的值
var account=document.getElementById("account").value;
//alert("测试获取文本框的值:"+account);
//先创建XMLHttpRequest对象
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//服务器地址和数据
var url="system/usercheck?account="+account;
//规定请求的类型、URL 以及是否异步处理请求。
xmlHttp.open("GET",url,true);
//将请求发送到服务器
xmlHttp.send();
//回调函数
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
//给div设置内容
document.getElementById("errorAccount").innerHTML = xmlHttp.responseText;
}
}
//给div设置内容
//document.getElementById("errorAccount").innerHTML=account;
}
</script>
</head>
<body bgcolor="#CCFF00"> <center>
<form action="" method="post">
<table>
<caption>注册的页面</caption>
<tr>
<td>账号:</td>
<td>
<input type="text" name="account" id="account" onblur="checkIt()"/>
<div id="errorAccount" style="color:red;display:inline;"></div>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

    1.2:实现后台模拟数据库登陆的Servlet页面,源码如下,类名是UserCheckServlet.java

 package com.bie;

 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; /**
* @author BieHongLi
* @version 创建时间:2017年3月2日 下午9:06:46
*
*/
@WebServlet("/system/usercheck")
public class UserCheckServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码集
request.setCharacterEncoding("utf-8");
//模拟存在数据库里面的账号
String[] arr={"张三","李四","王五","admin","小别"};
//获取前台传来的数据
String account=request.getParameter("account"); //模拟和数据库里面的信息匹配
boolean mark=false;
for(String user:arr){
if(user.equals(account)){
mark=true;
break;
}
} //响应前台
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(mark){
out.println("<font color='red'>该帐号已经存在,请重新输入!</font>");
}else{
out.println("<font color='green'>恭喜您,该帐号可以使用!</font>");
}
out.flush();//刷新流
out.close();//关闭流 } }

效果如下所示:


  1.3:第二种方式,使用post方式发送服务器请求;还如上所示,先写一个jsp页面,如register2.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=UTF-8">
<title>注册的页面</title>
<script type="text/javascript">
//onblur失去焦点的值 //定义一个变量用于存放XMLHttpRequest对象
var xmlHttp;
function checkIt(){
//获取文本框的值
var account=document.getElementById("account").value;
//alert("测试获取文本框的值:"+account);
//先创建XMLHttpRequest对象
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//服务器地址和数据
var url = "system/usercheck";
//规定请求的类型、URL 以及是否异步处理请求。
xmlHttp.open("POST",url,true);
//向请求添加 HTTP 头。这个必加,是提交到后台的方式
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//将请求发送到服务器
xmlHttp.send("account="+account);
//回调函数
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
//给div设置内容
document.getElementById("errorAccount").innerHTML = xmlHttp.responseText;
}
}
//给div设置内容
//document.getElementById("errorAccount").innerHTML=account;
}
</script>
</head>
<body bgcolor="#CCFF00"> <center>
<form action="" method="post">
<table>
<caption>注册的页面</caption>
<tr>
<td>账号:</td>
<td>
<input type="text" name="account" id="account" onblur="checkIt()"/>
<div id="errorAccount" style="color:red;display:inline;"></div>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

  1.4:然后写后台,依旧如上所示;如UserCheckServlet.java

 package com.bie;

 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; /**
* @author BieHongLi
* @version 创建时间:2017年3月2日 下午9:06:46
*
*/
@WebServlet("/system/usercheck")
public class UserCheckServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码集
request.setCharacterEncoding("utf-8");
//模拟存在数据库里面的账号
String[] arr={"张三","李四","王五","admin","小别"};
//获取前台传来的数据
String account=request.getParameter("account"); //模拟和数据库里面的信息匹配
boolean mark=false;
for(String user:arr){
if(user.equals(account)){
mark=true;
break;
}
} //响应前台
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(mark){
out.println("<font color='red'>该帐号已经存在,请重新输入!</font>");
}else{
out.println("<font color='green'>恭喜您,该帐号可以使用!</font>");
}
out.flush();//刷新流
out.close();//关闭流 } }

演示效果如下所示:


2:使用jQuery进行异步请求验证,在开发中最常使用,实际开发过程中必须会使用的技术;

  推荐一个jQuery在线api的网站(挺不错的在线查看api,也可以下载,我用着挺方便的):http://jquery.cuishifeng.cn/ 

  2.1:下面介绍如何使jQuery进行开发,需要注意的是要引入一个jQuery的js,如下:

    <script type="text/javascript" src="js/jquery.min.js"></script>

   2.2:如上,依旧先创建一个register3.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=UTF-8">
<title>注册的页面</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//给账号文本框绑定失去焦点的事件
$("#account").blur(function(){
//alert("测试"+$(this).val());
$.ajax({
url:"system/usercheck",//设置服务器地址,即为servlet配置的url-pattern
type:"post",//提交的方式
data:{account:$(this).val()},//提交到服务器的数据,多个值以逗号分割开{account:$(this).val(),...}
success:function(data){//回调函数,data是返回的数据
$("#errorAccount").html(data);
}
});
});
}); </script>
</head>
<body bgcolor="#CCFF00"> <center>
<form action="" method="post">
<table>
<caption>注册的页面</caption>
<tr>
<td>账号:</td>
<td>
<input type="text" name="account" id="account" onblur="checkIt()"/>
<div id="errorAccount" style="color:red;display:inline;"></div>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

  2.3:后台servlet代码依旧如上面的模拟数据库,代码如下所示:

 package com.bie;

 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; /**
* @author BieHongLi
* @version 创建时间:2017年3月2日 下午9:06:46
*
*/
@WebServlet("/system/usercheck")
public class UserCheckServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码集
request.setCharacterEncoding("utf-8");
//模拟存在数据库里面的账号
String[] arr={"张三","李四","王五","admin","小别"};
//获取前台传来的数据
String account=request.getParameter("account"); //模拟和数据库里面的信息匹配
boolean mark=false;
for(String user:arr){
if(user.equals(account)){
mark=true;
break;
}
} //响应前台
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(mark){
out.println("<font color='red'>该帐号已经存在,请重新输入!</font>");
}else{
out.println("<font color='green'>恭喜您,该帐号可以使用!</font>");
}
out.flush();//刷新流
out.close();//关闭流 } }

演示效果如下所示:


3:如果说还有更加适合进行异步验证的方法,那么就是下面这种,直接使用post进行异步验证,理解其原理,异步验证so easy!!!

  3.1:首先创建一个页面register4.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=UTF-8">
<title>注册的页面</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//异步验证
$("#account").blur(function(){
$.post("system/usercheck2",{account:$(this).val()},
function(data){
if(data=="true"){
//如果已经存在,提示账号已经被注册
$("#errorAccount").html("账号已被注册,请重新输入!");
}else{
//这里可以注册的可以不进行提示,清空即可
$("#errorAccount").html("<font color='green'>账号可以注册哟!</font>");
}
},"text");
});
}); </script>
</head>
<body bgcolor="#CCFF00"> <center>
<form action="" method="post">
<table>
<caption>注册的页面</caption>
<tr>
<td>账号:</td>
<td>
<input type="text" name="account" id="account" onblur="checkIt()"/>
<div id="errorAccount" style="color:red;display:inline;"></div>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

  3.2:这次的servlet后台处理虽然依旧是模拟数据库,但是操作却不一样了。需要注意一下;

 package com.bie.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; /**
* @author BieHongLi
* @version 创建时间:2017年3月2日 下午9:06:46
*
*/
@WebServlet("/system/usercheck2")
public class UserCheckServlet2 extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码集
request.setCharacterEncoding("utf-8");
//模拟存在数据库里面的账号
String[] arr={"张三","李四","王五","admin","小别"};
//获取前台传来的数据
String account=request.getParameter("account"); //模拟和数据库里面的信息匹配
boolean mark=false;
for(String user:arr){
if(user.equals(account)){
mark=true;
break;
}
} //响应前台
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(mark){
out.print("true");
}else{
out.print("false");
}
out.flush();//刷新流
out.close();//关闭流 } }

演示效果如下所示:


革命尚未成功,别同志尚需努力啊!

最新文章

  1. Redis 做消息队列
  2. 开启SharePoint Server 2013 中的“微博”功能——新闻源
  3. xml文件格式说明
  4. PDO多种方式取得查询结果
  5. 让Entity Framework支持MySql数据库(转载)
  6. 剑指Offer:面试题4——替换空格(java实现)
  7. Protocol-RS-232/422/485标准
  8. Redis pipeline and list
  9. 卸载 Cloudera Manager 5.1.x.和 相关软件【官网翻译】
  10. VMware:虚拟机磁盘空间不足怎么办
  11. (转)__dopostback的用法 .
  12. Qt跨线程信号和槽的连接(默认方式是直连和队列的折中)
  13. HBase总结(二十)HBase经常使用shell命令具体说明
  14. Spring使用@Scheduled定时调度
  15. Detours HOOK 库 过滤LoadLibraryExW
  16. 阿里云入坑指南&amp;&amp;nodejs 安装配置
  17. 五子棋(无AI winform gdi+)
  18. js备忘录2
  19. TED #03# 10 ways to have a better conversation
  20. 剪邮票--蓝桥杯--dfs--思路超清晰

热门文章

  1. java字符串转义,把&amp;lt;&amp;gt;转换成&lt;&gt;等字符【原】
  2. ObservableData-另一种姿势的观察者模式
  3. Newtonsoft.Json 两个Attribute含义
  4. KillerBee
  5. nlogn LIS模板
  6. 进度条QProgressBar
  7. F - New Distinct Substrings (后缀数组)
  8. SpringMVC与Struts不同(五)
  9. MYSQL和oracle 大小写问题
  10. css 背景图片自适应元素大小