1、建立form.html文件,在body中输入表单代码,并导入jquery包和form.js包
<form action="" method="post" id="regForm">
<pre>
用户名:<input type='text' name='userName'><span id="s1"></span>
密码:<input type='password' name='userPassword'>
确认密码:<input type='password' name='repwd'>
<input type='submit' name='sub' value="注册">
</pre>
</form>
导入jquery包和form.js包
<script src="js/jquery1.11.3.min.js"></script>
<script src="js/form.js"></script>
2、建立服务器端servlet文件checkformServlet.servlet,在doGet()里面写入以下代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//禁用缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out = response.getWriter();
String userName=request.getParameter("userName");
String userPassword=request.getParameter("userPassword");
out.println("接收到了客户端提交的"+userName+","+userPassword);
}
3、建立客户端form.js代码
$(function(){
$(":submit[name='sub']").click(function(){
//alert($("#regForm").serialize());
$data=$("#regForm").serialize();
$.ajax({
type:"post",
url:"checkformServlet",
data:$data,
success:function(msg){
alert(msg);
}
})
})
})