[JS] Form表单提交时:即使用原生html5验证,又使用ajax提交数据

没事都是无法理解Form的原理,不喜欢自动提交数据。但是又喜欢html5 原生对于input(特殊类型)的判断,

所以需要可以找到点击button (type=submit)时,可以做到:

  1. html5 自带表单验证
  2. 使用ajax提交数据,因为后台返回是Json

 

HTML 代码部分:

使用了Bootstrap 4.2 

<form id="login_form">
                    <div class="form-group row">
                        <label for="login_email" class="col-sm-4 col-form-label">*Email</label>
                        <div class="col-sm-8">
                            <input type="email" class="form-control" id="login_email" aria-describedby="emailHelp"
                                   placeholder="username@aaa.com">
                        </div>

                    </div>
                    <div class="form-group row">
                        <label for="login_password" class="col-sm-4 col-form-label">*Password</label>
                        <div class="col-sm-8">
                            <input type="password" class="form-control" id="login_password" placeholder="Password">
                        </div>
                    </div>

                    <!--Error Msg Part-->
                    <div id="login_error_msg" class="alert alert-danger" role="alert"></div>

                    <div class="row">
                        <div class="col-sm-4 offset-sm-9">
                            <button type="submit" class="btn btn-primary">
                                 <i class="fas fa-sign-in-alt"></i> 登陆
                            </button>
                        </div>
                    </div>
                </form>
View Code

 

JS 代码部分:

$("#login_form").on('submit', function (ev) {
            // html5 原生 validation
            ev.preventDefault();

            // POST data,自己Ajax
            var data = {
                'email': $("#login_email").val().trim(),
                'password': $("#login_password").val().trim(),
            };

            //$("#login_main").mask("认证中...");
            $.ajax({
                type: "POST",
                url: "/login/",
                data: data,
                dataType: 'json',
                success: function (result) {
                    // do something 
                },
                complete: function () {
                    // $("#login_main").unmask("认证中...");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.status + " >>> " + textStatus + "\n" + XMLHttpRequest.responseText);
                },
            });
        })

 

 

完美的解决了我的需求~~JS部分还是不是很熟,也是从别人那里找到的代码。。有时间搞懂为啥这么写~~~

posted @ 2019-03-22 12:31  小小Guido妹  阅读(351)  评论(0编辑  收藏  举报