亚洲欧美日韩综合系列在线_91精品人妻一区二区_欧美大肥婆一级特大AA片_九色91视频免费观看_亚洲综合国产精品_av中文字幕在线不卡_久久精品色综合网_看黄色视频的软件_无卡无码高清中文字幕码2024_亚洲欧美日韩天堂网

bootstrap模態(tài)框——使用一個模態(tài)框完成兩個功能

來源:Eve慕 發(fā)布時間:2018-07-02 15:23:31 閱讀量:1526

在用戶列表中希望能用同一個模態(tài)框完成添加用戶和修改用戶兩個功能。

添加界面
添加用戶 
修改用戶
修改用戶

這兩個功能在提交表單之后都會返回原頁面,所以使用ajax進行處理 
主要的難點在于: 
1、在點擊不同按鈕時調用不同函數(shù)。 
在點擊修改頁面時,需要將當前用戶的信息傳入模態(tài)框中,并設置用戶名字段為不可修改,點擊模態(tài)框中提交時調用后臺修改的方法;在點擊添加頁面時,需要清空之前模態(tài)框中數(shù)據,點擊提交按鈕時,調用的是后臺中添加的方法。 
2、不同功能的表單驗證不同。 
表單驗證使用jQuery validate插件。在添加時,需要驗證用戶名不為空、長度和是否重復。而修改時不需要對用戶名做驗證。所以需要自定義validate。 
3、關于用戶id的賦值。 
修改功能中,需要將當前表單內容和用戶id一起傳入后臺,才能進行修改。而添加時,由于在數(shù)據庫中將用戶id設為自增模式,所以不需要傳id的值,只傳其他字段的值即可。但是表單數(shù)據的傳輸是封裝好之后一起傳輸,所以要做額外處理。

前端代碼:

<!DOCTYPE html><html lang="en"  xmlns:th="http://www.thymeleaf.org"><head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用戶列表</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依賴 jQuery,所以必須放在前邊) -->
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <!-- 加載 Bootstrap 的所有 JavaScript 插件。你也可以根據需要只加載單個插件。 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--validate驗證表單插件-->
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script></head><script>
    //定義一個變量用于存儲添加和修改時不同的URL
    var myUrl;    //傳入點擊的用戶id,獲取該用戶信息并放入表單中
    function update(id) {
        //將提交表單的URL變?yōu)閡pdate
        myUrl = '/updateUser';        if(!id){
            alert('id錯誤');            return false;
        }

        $.ajax(
                {
                    url:"/toUpdateUser",
                    data:{"id":id},
                    type:"post",                    //解決編碼問題
                    scriptCharset: 'utf-8',
                    beforeSend:function () {
                        return true;
                    },
                    success:function (data) {
                        if(data){                            //解析json數(shù)據
                            var data = data;                            var user = eval("("+data + ")");                            //賦值
                            $('#userID').val(user.userID);
                            $('#username').val(user.username);
                            $('#password').val(user.password);
                            $('#phone').val(user.phone);
                            $('#email').val(user.email);                            //在修改用戶信息時,username不可修改
                            $('#username').attr("readonly","readonly");
                        }
                    }
        });
    }    //表單字段驗證
    //如果按照一般驗證的寫法,只能調用整個表單的validate函數(shù),而不能調用自定義的username驗證,所以把兩個函數(shù)封裝成為一個,在點擊按鈕時調用
    function vali() {
        //form-data表單驗證。
        $("#form-data").validate({
            onfocusout:function(element) { $(element).valid(); },
            onblur: function(element) { $(element).valid(); },    //鼠標移開驗證。這里寫onblue:true沒有效果
            onsubmit:true,      //提交時驗證(有效)
            onkeyup:false,

            rules:{
                password:{
                    required:true,
                    rangelength:[5,20]
                },
                phone:{
                    required:true,
                    digits:true,
                    rangelength:[11,11]
                },
                email:{
                    required:true,
                    email:true
                }
            },
            messages:{
                password:{
                    required:"請?zhí)顚懨艽a",
                    rangelength:"密碼長度不符合規(guī)范"
                },
                phone:{
                    required:"請?zhí)顚懯謾C號",
                    digits:"請?zhí)顚懻_的手機號",
                    rangelength:"請?zhí)顚懻_的手機號"
                },
                email:{
                    required:"請?zhí)顚戉]箱",
                    email:"請?zhí)顚懻_的郵箱"
                }
            },
            submitHandler:function (form) {
                checkForm();
            }
        });        //自定義動態(tài)username驗證
        //username的校驗只在添加操作時才需要
        //通過對username的readonly屬性驗證來判斷是添加還是更新
        if($('#username').attr("readonly")==undefined){
            $('#username').rules("add",{
                required:true,
                rangelength:[5,20],
                remote: {
                    type: "POST",
                    url: "/checkUsername",
                    data: {
                        username: function () {
                            return $("#username").val();
                        }
                    },
                    dataType: "html",
                    dataFilter: function(data) {
                        if (data == "true")                            return true;                        else
                            return false;
                    }
                },
                messages:{
                    required:"請?zhí)顚懹脩裘?quot;,
                    remote:"用戶名已存在",
                    rangelength:"用戶名長度不符合規(guī)范"
                }
            });
        }
    }    /*
    點擊添加用戶時需要做的操作:
        1.修改提交表單的URL
        2.將username的readonly屬性移除
        3.清空表單數(shù)據
     */
    function setUrl() {
        myUrl='/addUser';
        $('#username').removeAttr("readonly");
        $('#form-data input').val(" ");
    }    //提交表單
    function checkForm() {

        var formData;        //將表單內容序列化,即可得到相應對象,直接傳到后臺
        //userid為空時,即當前操作為添加用戶操作,此時只序列化除id之外四個屬性,添加用戶時id自增長。如果id為空也被序列化會報錯
        if($('#userID').val()==null||$('#userID').val()==undefined||$('#userID').val().length==0){
            formData = $('#username,#password,#email,#phone').serializeArray();
        }        //否則為更新操作,userid為隱藏input,并且已經被賦值,序列化整個表單即可
        else{
            formData = $('#form-data').serializeArray();
        }

        $.ajax({
                url:myUrl,      //根據操作傳入不同的URL
                data:formData,  //傳入序列化的表單對象
                type:"post",
                datatype:'text',
                async:false,    //異步傳輸
                timeout:50000,                //設置編碼
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                beforeSend:function () {
                    $('#tip').html('<span style="color: cornflowerblue">正在處理...</span>');                    return true;
                },
                success:function (data) {
                    if(data > 0){
                        $('#tip').html('<span style="color: green">操作成功!</span>');
                        location.reload();
                    }else{
                        $('#tip').html('<span style="color: red">操作失敗,請重試</span>');
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                    // alert(XMLHttpRequest.status);//狀態(tài)碼
                    // alert(XMLHttpRequest.readyState);//狀態(tài)
                    // alert(textStatus);//錯誤信息
                    alert("出錯了");

                },
                complete:function () {

                }
                });
    }</script><body><div class="container-fluid">
    <div class="tool">
        <div class="row">
            <form action="" class="form-horizontal">

            <div class="col-sm-3">
                <input type="text" id="search" class="form-control">
            </div>
            <div class="col-sm-1">
                <button type="submit" class="btn btn-primary">搜索</button>
            </div>
            </form>
            <div class="col-sm-4">

            </div>
            <div class="col-sm-2">
                <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#updateModal" onclick="setUrl()">添加用戶</button>
            </div>
        </div>
    </div>
    <br>
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>id</th>
                <th>用戶名</th>
                <th>密碼</th>
                <th>電話</th>
                <th>郵箱</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody >
            <tr th:each="user : ${userlist}">
                <td th:text="${user.userID}"></td>
                <td th:text="${user.username}"></td>
                <td th:text="${user.password}"></td>
                <td th:text="${user.phone}"></td>
                <td th:text="${user.email}"></td>
                <td>
                    <!--傳入當前用戶id-->
                    <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#updateModal" th:onclick="'javascript: update('+${user.userID}+')' ">編輯</button>
                    <button type="button" class="btn btn-danger btn-sm"  th:onclick="'javascript:deleteUser('+${user.userID}+')' ">刪除</button>
                </td>
            </tr>
        </tbody>
    </table>
    <!--模態(tài)框-->
    <form method="post" name="user" class="form-horizontal" role="form" id="form-data"  style="margin: 20px;" >
    <div class="modal fade" id="updateModal"   tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;                    </button>
                    <h4 class="modal-title" id="updateModalLabel">
                        用戶信息                    </h4>
                </div>
                <div class="modal-body">
                    <form action="" class="form-horizontal">
                        <!--userid為隱藏的input,便于update時的傳值-->
                        <input type="text" id="userID" name="userID" hidden>
                        <div class="form-group">
                            <label for="username" class="col-sm-3 control-label">用戶名</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="username" name="username" placeholder="用戶名長度在5-18字符之間">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="password" class="col-sm-3 control-label">密碼</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="password" name="password" placeholder="密碼長度在5-20字符之間">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="phone" class="col-sm-3 control-label">手機號</label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="phone" name="phone" placeholder="請輸入手機號">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="email" class="col-sm-3 control-label">郵箱</label>
                            <div class="col-sm-9">
                                <input type="email" class="form-control" id="email" name="email" placeholder="請輸入郵箱地址">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
                    <!--type為submit時,會自動調用該表單的驗證,但是不會調用自己定義的動態(tài)的username的驗證,
                    所以把按鈕類型改為input,再手動調用封裝好的驗證函數(shù)-->
                    <button type="input" class="btn btn-primary" onclick="vali();">提交</button>
                    <span id="tip"></span>
                </div>
            </div>
        </div>
    </div>
    </form></div><div th:insert="template/footer :: copyright"></div></body></html>

原文地址https://blog.csdn.net/zxm490484080/article/details/80859485

標簽: HTML JS
分享:
評論:
你還沒有登錄,請先