步骤:
<!--
1.导入jQuery包
2:获取 name="username"的节点,为该节点添加change()相应函数
3:获取username的属性值,去处前后空格,当不为空的时候,准备发送ajax请求
4:发送ajax请求,url为servlet,agrs为传递的json参数,该参数是像servlet中传递的,检验用户名是否可用
5:在服务端接受ajax传来的Json数据,并处理,结果返回一个html片段,将其添加到#message中。
-->
<%@ page language="java" pageEncoding="UTF-8"%>
<html:html lang="true">
<head>
<!--${pageContext.request.contextPath}获取该项目的绝对路径 -->
<script type="text/javascript"
src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$(":input[name='username']").change(function(){
var val=$(this).val(); //获取username节点中的value属性值
val=$.trim(val); //取出前后空格
if(val!=""){
var url="${pageContext.request.contextPath}/valiateUserName";
var agrs={"userNamesyq":val,"time":new Date()}; //准备传递的参数,注意该参数的类型设置为json格式的
$.post(url,agrs,function(data){
$("#message").html(data); //设置id="message"中的内容为data
});
}
});
});
</script>
</head>
<body>
<form action="" method="post">
UserName:
<input type="text" name="username" />
<br>
<br>
<div id="message"></div>
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html:html>
servlet中检验用户名是否正确,并发送一个html片段给ajax
public class ValiateUserName extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<String> list=Arrays.asList("aaa","bbb","ccc");
String userName=request.getParameter("userNamesyq"); //获取从ajax中传来的属性值,该数据是从ajax中的json中传来的
System.out.println(userName+"**********");
String result=null;
if(list.contains(userName)){
result="<font color='red'>该用户名已经被使用</font>";
}else{
result="<font color='green'>该用户名可以使用</font>";
}
response.setCharacterEncoding("UTF-8"); //解决中文乱码现象
response.setContentType("text/html"); //设置传回数据的类型
response.getWriter().print(result); //传回html数据
}
}
实际上对用户名的检验要从数据库打交道,本程序只是讲解ajax检验用户名是否可用的原理。