1.导入jQuery包
2.编写servlet
public class checkServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
if("scott".equals(name)){
out.println("用户名已被占用");
}else{
out.println("用户名可用");
}
out.flush();
out.close();
}
}
3.在web.xml中配置servlet
<servlet>
<servlet-name>checkServlet</servlet-name>
<servlet-class>checkServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkServlet</servlet-name>
<url-pattern>/check.do</url-pattern>
</servlet-mapping>
4.编写index.jsp界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#username").blur(function(){
var name = $("#username").val();
$("#username_msg").html("正在检测...");
$.ajax({
url:"check.do",
type:"post",
data:{"name":name},
success:function(result){
$("#username_msg").html(result);
}
});
});
});
</script>
</head>
<body>
<input type="text" id="username">
<span id="username_msg"></span>
</body>
</html>
5.实现的效果
6.总结
使用jQuery比直接使用js更方面,有些功能已经被封装了,可以直接使用~~
这样操作ajax更简单