<%@ 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>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(":input[name='username']").change(function(){
var name=$(this).val();
name=$.trim(name);
if(name!=""){
var url="{pageContext.request.pageContext}/loginServlet";
//var arg={"username":name,"time":new Data()};
var arg={};
$.post(url,arg,function(data){
$("#message").html(data);
});
}
});
});
</script>
</head>
<body>
<form action="loginServlet" method="post">
<input type="text" name="username"/>
<div id="message"></div>
<input type="submit" name="btn" />
</form>
</body>
</html>
3. jQuery.post( url, [data], [callback], [type] ) :使用POST方式来进行异步请求
jquery $.post 方法参数列表(说明):
url (String) : 发送请求的URL地址.
data (Map) : ( 可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示,可将此值放到url中。
callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才能调用该方法)。
type (String) : (可选)客户端请求的数据类型(JSON,XML,等等)
loginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List list=new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
String username=request.getParameter("username");
System.out.println(username);
String result=null;
if(list.contains(username)){
System.out.println("用户名已存在");
result= "<font color='red'> 用户名已存在</font>" ;
}else{
result= "<font color='green'> 用户名bu存在</font>" ;
}
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
response.getWriter().print(result);
}