/** * 使用ajax提交表单,并接收返回值,根据返回值产生提示 */ function subForm(){ alert($("#basePath").val()); $.ajax({ url : $("#basePath").val()+"servlet/RegisterServlet", dataType : "text", data : {"username":$("#user").val(),"password":$("#pass").val(),"again":$("#again").val(),"captcha":$("#captcha")}, timeout : 1000, type : "POST", success : function(data){ } }); }
接收的Servlet代码
package cn.edu.tjut.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.edu.tjut.service.RegisterService; public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("接收正常"); response.setContentType("text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); //从request中取出参数 String captcha = request.getParameter("captcha"); String username = request.getParameter("username"); String password = request.getParameter("password"); String again = request.getParameter("again"); //获取验证码值 String checkcode = (String)request.getSession().getAttribute("checkcode"); //验证验证码是否正确 if(!captcha.equals(checkcode)){ pw.print(-1); pw.flush(); pw.close(); return; } //检查两次输入密码是否一致 if(!password.equals(again)){ pw.print(-2); pw.flush(); pw.close(); return; } RegisterService rs = new RegisterService(); int res = rs.addUser(username, password); //验证添加是否成功 if(res==0){ pw.print(0); pw.flush(); pw.close(); request.getRequestDispatcher("/login.jsp").forward(request, response); } pw.print(res); pw.flush(); pw.close(); } }
控制台并没有输出接收正常
sntatas
sntatas
相关分类