Layui環境下form表單提交;jquery.form.js;lay-verify,lay-filter;

花繁柳密處發表於2020-11-29

話不多說,直接看程式碼:

引入相關文件:

<script th:src="@{/js/jquery-1.9.1.js}"></script>
<script th:src="@{/js/jquery.form.js}"></script>
<script src="/layui/layui.js"></script>
<link rel="stylesheet" href="/layui/css/layui.css">

(這裡會使用jquery.form.js進行表單提交)

Form表格部分:

<form id="upload_form" action="/upload" class="layui-form">
	<div class="layui-form-item">
        <label for="name" class="layui-form-label">姓名:</label>
        <input type="text" name="name" id="name" lay-verify="name">
    </div>
    <div class="layui-form-item">
        <label for="sex" class="layui-form-label">性別:</label>
        <select id="sex" name="sex" lay-filter="sex" lay-verify="sex">
            <option value="0">請選擇</option>
            <option value="1"></option>
            <option value="2"></option>
        </select>
    </div>
    <div class="layui-form-item">
        <label for="type" class="layui-form-label">型別:</label>
        <select id="type" name="type" lay-filter="type" lay-verify="type">
            <option value="0">請選擇</option>
        </select>
    </div>
    <div class="layui-form-item">
        <label for="phone" class="layui-form-label">手機:</label>
        <input type="text" name="phone" id="phone" lay-verify="phone">
    </div>
    <div class="layui-form-item">
        <label for="birthday" class="layui-form-label">生日:</label>
        <input type="text" name="birthday" id="birthday" lay-verify="birthday">
    </div>
    <div class="layui-form-item">
        <button id="submit" lay-submit="" lay-filter="submit" onclick="initCanSubmit()">儲存</button>
    </div>
</form>

需要注意的點:

  1. form標籤需要新增class="layui-form",否則以下關於form的相關操作無效;
  2. lay-verify用於表單校驗,並且需要在提交按鈕中新增lay-submit="";
  3. lay-filter相當於一個選擇器,比如lay-filter="sex"lay-filter="type"就將兩組<select>區分開來,而form.on中第一個引數的小括號中的值也對應了lay-filter的值;

JavaScript部分:

var can_submit=true;// 通過此值判斷是否通過校驗
function initCanSubmit() {// 在每次點選儲存按鈕時首先初始化can_submit值
    can_submit=true;
}
$(function(){
    <!--引入laydate模組-->
    layui.use('laydate', function(){
        var laydate=layui.laydate;
        laydate.render({
            elem: '#birthday'
        });
    });
    <!--引入form模組-->
    layui.use(['form'],function(){
        var form=layui.form;

        <!--id="sex"的select被改變時,對id="type"的select進行重新整理-->
        form.on('select(sex)', function(data){
            $.ajax({
                type: 'POST',
                data: {
                    val: data.value
                },
                url: '/onSelect',
                success: function(r){
                    if(r && r.success){
                        $('#type').empty();
                        var opt = document.createElement('option');
                        opt.value = '0';
                        opt.innerText = '請選擇';
                        $('#type').append(opt);
                        $.each(r.data, function(index, item){
                            opt = document.createElement('option');
                            opt.value = item.val;
                            opt.innerText = item.key;
                            $('#type').append(opt);
                        });
                        form.render();// 渲染重新整理
                    }
                }
            });
        })
        // 表單校驗
        var phoneReg = new RegExp("^0?(13|14|15|18)[0-9]{9}");
        form.verify({
            name: function(value){
                if(value==""){
                    layer.msg("請填寫名稱");
                    can_submit=false;
                }
            },
            sex: function(value){
                if(can_submit && (value=="" || value==0)) {
                    layer.msg("請選擇性別");
                    can_submit=false;
                }
            },
            type: function(value){
                if(can_submit && (value=="" || value==0)) {
                    layer.msg("請選擇型別");
                    can_submit=false;
                }
            },
            phone: function(value){
                if(can_submit && (value=="" || !phoneReg.test(value))){
                    layer.msg("請填寫手機號");
                    can_submit=false;
                }
            },
            birthday: function(value){
                if(can_submit && value==""){
                    layer.msg("請填寫生日");
                    can_submit=false;
                }
            }
        })
        // 表單提交
        form.on('submit(submit)', function(data){
            if(can_submit){
                $("#upload_form").ajaxForm(function (r) {//??
                    if (r && r.success) {
                        window.location.href="/index";
                    } else {
                        layer.msg(r.msg);
                    }
                })
            } else {
                return false;// 表單提交失效
            }
        })
    });
})

需要注意的點:

  1. form.verify要放在form.on外面,否則不觸發;
  2. 若想要表單提交失效,必須在form.on中return false;

另外,還想向各位大神請教:
$("#upload_form").ajaxForm(function (r) {這一行程式碼,起初在公司專案中使用ajaxSubmit可正常提交form,而在自己的練習專案中變為了使用ajaxForm才能正常提交form,請問問題出在哪裡?

附:相關後端程式碼:
Controller:

@RequestMapping("/upload")
@ResponseBody
public JsonModel upload(String name, Integer sex, Integer type, String phone, String birthday){
    System.out.println(name);
    System.out.println(sex);
    System.out.println(type);
    System.out.println(phone);
    System.out.println(birthday);

    return new JsonModel(true, "提交成功");
}

@RequestMapping("/onSelect")
@ResponseBody
public JsonModel onSelect(Integer val) {
    JsonModel js = new JsonModel(true, "");
    List<SelectOption> list = new ArrayList<>();
    if (val==1) {
        SelectOption so1 = new SelectOption("孔明", "1");
        SelectOption so2 = new SelectOption("劉備", "2");
        list.add(so1);
        list.add(so2);
    } else if (val==2) {
        SelectOption so3 = new SelectOption("嫦娥", "3");
        SelectOption so4 = new SelectOption("武瞾", "4");
        list.add(so3);
        list.add(so4);
    }
    js.setData(list);
    return js;
}

工具類:

public class SelectOption implements Serializable {
	private static final long serialVersionUID=1L;
	
	private String key;
	private Object val;
	......
}

相關文章