方法位置
<FORM id=form1 name=form1 action = "${pageContext.request.contextPath }/user_regist.action" onsubmit="return checkForm()" method=post>
<TR>
<TD style="HEIGHT: 28px" width=80>登 录 名:</TD>
<TD style="HEIGHT: 28px" width=150><INPUT id=user_code
style="WIDTH: 130px" name=user_code onblur="checkCode()"></TD>
<TD style="HEIGHT: 28px" width=370><SPAN
id=codeId
style="FONT-WEIGHT: bold; "></SPAN></TD></TR>
<!-- 引入JQ --> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script> <script type="text/javascript"> function checkCode() { //获取到用户输入的用户名 var code = $("#user_code").val(); //进行判断 if(code.trim()==""){ //给提示 $("#codeId").addClass("error"); $("#codeId").html("登录名不能为空"); }else{ //登录名不为空 ajax var url = "${pageContext.request.contextPath }/user_checkCode.action"; var param = {"user_code":code}; $.post(url,param,function(data){ //操作data,进行判断 if(data&&data=="no"){ //提示 $("#codeId").addClass("error"); $("#codeId").html("登录名已经存在"); }else{ $("#codeId").removeClass("error"); $("#codeId").html("可以注册"); } }); } } function checkForm(){ //先让校验名称的方法执行下 checkCode(); //获取error, if($(".error").size()>0){ return false; } } </script>
ajax的javaAction代码
//根据登录名判断是否存在 public String checkCode(){ //调用业务层,查询 User u = userService.checkCode(user.getUser_code()); //获取response对象 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); //获取输出流 try { PrintWriter writer = response.getWriter(); if (u!=null) { //cunzai writer.print("no"); }else { //不存在 可以注册 writer.print("yes"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return NONE; }