JQuery.validate验证表单后Ajax异步提交
生活随笔
收集整理的這篇文章主要介紹了
JQuery.validate验证表单后Ajax异步提交
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一、前言
本文主要介紹jquery.validate+jquery.form實現表單驗證,然后用Ajax方式異步提交。本文重在介紹前端技術,故省略和數據庫交互部分。后端僅提供Controller代碼來模擬效果。
第二、場景
用戶注冊時,錄入個人信息后,做表單驗證,然后提交。
第三、代碼示例
1、新建web Project,命名:Examination1,引入Spring MVC相關jar包。下面僅提供jar包截圖,請讀者自行下載,若個人無法自行下載,可在文章下留言向本人索要相關jar包。
2、引入jquery.validate+jquery.form開發工具包
下載地址:jquery.validate+jquery.form.rar
3、修改web.xml
4、新建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- spring容器掃描指定包下的所有類,如果類上有注解 那么根據注解產生相應bean對象已經映射信息 --><context:component-scan base-package="com.exam"/> </beans>5、新建mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 配置視圖渲染器 --><bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><!-- 渲染后視圖的后綴 --><property name="suffix" value=".jsp"/></bean><!-- spring容器掃描指定包下的所有類,如果類上有注解 那么根據注解產生相應bean對象已經映射信息 --><context:component-scan base-package="com.exam"/><mvc:annotation-driven></mvc:annotation-driven><!-- 靜態資源 --><mvc:resources location="/js/" mapping="/js/**"></mvc:resources><mvc:resources location="/script/" mapping="/script/**"></mvc:resources><mvc:resources location="/style/" mapping="/style/**"></mvc:resources> </beans>6、新建com.exam.dto.UserDTO
import java.io.Serializable; /*** 用戶實體* @author shixiangcheng* 2020-08-08*/ public class UserDTO implements Serializable{private static final long serialVersionUID = -5905162223331046615L;private String loginName;//登錄名private String name;//姓名private String password;//密碼private String email;//郵箱private String phone;//手機號public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getName() {return name;}public void setName(String name) {this.name = name;} }7、新建com.exam.controller.UserController
import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.exam.dto.UserDTO; /*** 用戶信息管理* @author shixiangcheng* 2020-08-08*/ @Controller @RequestMapping("/user") public class UserController {//增加用戶@RequestMapping(value="/add")@ResponseBodypublic Map<String,Object> add(UserDTO userDTO,HttpServletRequest request,HttpServletResponse response)throws Exception{userDTO.setName(URLDecoder.decode(userDTO.getName(),"UTF-8").trim());//調用Service方法保存數據Map<String,Object> map=new HashMap<String,Object>();map.put("status", "success");return map;}//校驗用戶名是否存在@RequestMapping(value="/verifyLoginName")@ResponseBodypublic boolean verifyLoginName(HttpServletRequest request,HttpServletResponse response){String loginName=request.getParameter("loginName");if(StringUtils.isEmpty(loginName)) {return false;}//調用Service方法判斷用戶名是否存在,此處簡寫if("admin".equals(loginName)) {return false;}return true;} }8、新建index.jsp
<%@ page contentType="text/html;charset=UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用戶注冊</title> <script type="text/javascript" src="<%=request.getContextPath()%>/script/jquery.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/script/jquery_validate/jquery.metadata.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/script/jquery_validate/jquery.validate.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/script/jquery_validate/jquery.form.js"></script> <script type="text/javascript"> $(function(){//得到校驗規則的返回值,確保校驗規則都通過后再提交var validator=$("#form1").validate({rules: {loginName:{required:true,minlength:3,maxlength:15,remote: {url: '<%=request.getContextPath()%>/user/verifyLoginName',type: 'post',data: {"loginName": function () {return $("#loginName").val()},}} },name:{required:true},phone:{required:true,number:true},email:{email:true},password:{required:true,minlength:5,maxlength:20},password2:{required:true,minlength:5,maxlength:20,equalTo:"#password"},},messages:{loginName:{required:"請填寫登錄名!",minlength:"登錄名至少為3個字符",maxlength:"登錄名至多為15個字符",remote: "登錄名已經存在!"},name:{required:"請填寫姓名!"},phone:{required:"請填寫手機號!",number:"手機號必須是數字!"},email:{email:"請填寫正確的E-mail!"},password:{required:"請填寫密碼!",minlength:"密碼長度不能小于5個字符",maxlength:"密碼長度不能大于20個字符"},password2:{required:"請再次輸入密碼!",minlength:"密碼長度不能小于5個字符",maxlength:"密碼長度不能大于20個字符",equalTo:"兩次輸入的新密碼不一致"},}});$("#form1").click(function(){//保證校驗規則都通過后再提交if(validator.form()){addUser();}}); }); //Ajax異步提交保存用戶信息 function addUser(){var v_loginName=$("#loginName").val();var v_name=encodeURI($("#name").val(),"UTF-8");var v_phone=$("#phone").val();var v_email=$("#email").val();var v_password=$("#password").val();$.ajax({url:'<%=request.getContextPath()%>/user/add',data:{loginName:v_loginName,name:v_name,phone:v_phone,email:v_email,password:v_password},type:'post',async:false,dataType:'json',success:function(data){alert("注冊成功!");},error:function(data,type, err){alert("請聯系系統管理員!");}});return false; } </script> </head> <body> <form id="form1" method="post"><table cellpadding="0" cellspacing="0" align="center"><caption>用戶注冊</caption><tr><td>登錄名<font color="red">*</font></td><td><input type="text" name="loginName" id="loginName"/>(登錄名要唯一)</td></tr><tr><td>姓名<font color="red">*</font></td><td><input type="text" name="name" id="name"/></td></tr><tr><td>手機號<font color="red">*</font></td><td><input type="text" name="phone" id="phone"/></td></tr><tr><td>E-mail</td><td><input type="text" name="email" id="email"/></td></tr><tr><td>密碼<font color="red">*</font></td><td><input type="password" name="password" id="password"/></td></tr><tr><td>再次輸入密碼<font color="red">*</font></td><td><input type="password" name="password2" id="password2"/></td></tr><tr><td colspan="2" align="center"><input type="button" name="button"value="提交" /></td></tr> </table> </form> </body> </html>9、運行
直接點提交,將會出發校驗
對登錄名有唯一校驗(異步)
錄完信息后提交
歡迎大家積極留言交流學習心得,點贊的人最美麗,謝謝!
總結
以上是生活随笔為你收集整理的JQuery.validate验证表单后Ajax异步提交的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一招破解外网访问公司内网svn服务器
- 下一篇: 通配符