【问题标题】:Ajax request is not working inside of boostrap form validationAjax 请求在引导表单验证中不起作用
【发布时间】:2021-10-20 08:02:46
【问题描述】:

我正在使用 Bootstrap 验证实现一个表单,我已经使验证工作没有问题,但是当所有验证都被验证并且是将数据发送到我的 API 的时刻,AJAX Post 不执行,catch 子句不执行不要出现任何错误,只有该部分的 ajax 部分不执行这是我的验证代码:

        (function () {
            'use strict';
            window.addEventListener('load', function () {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');
                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        } else {
                            try {
                                var data = {
                                    firstname: form.name.value,
                                    lastname: form.lastname.value,
                                    company: form.company.value,
                                    email: form.email.value,
                                    phone: form.phone.value,
                                    jobtitle: form.job.value,
                                    message: form.comments.value,
                                }

                                $.ajax({
                                    type: "POST",
                                    url: url,
                                    data: data
                                });
                            } catch (error) {
                                console.log(error)
                            }
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>

    <section class="section">
        <div class="container">
            <div class="row">
                <div class="col-12">
                    <h4 class="text-dark mb-0">Ponte en contacto :</h4>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="custom-form rounded border p-4 h-100">
                        <div id="message"></div>
                        <form class="row g-3 needs-validation" novalidate>
                            <div class="row">
                                <div class="col-6">
                                    <div class="form-group app-label">
                                        <label for="validationCustom01" class="text-muted">Nombre</label>
                                        <input name="name" id="validationCustom01" type="text"
                                            class="form-control resume" placeholder="Ingresa tu nombre" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese un nombre
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Apellido</label>
                                        <input name="lastname" id="lastname" type="text" class="form-control resume"
                                            placeholder="Ingresa tu apellido" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese un apellido
                                        </div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Numero de Teléfono</label>
                                        <input name="phone" id="phone1" type="phone" class="form-control resume"
                                            placeholder="Ingresa tu teléfono" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese un teléfono
                                        </div>
                                    </div>
                                </div>
                                <div class="col-8">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Correo Electrónico</label>
                                        <input name="email" id="email1" type="email" class="form-control resume"
                                            placeholder="Ingresa tu correo electrónico" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese un email valido
                                        </div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Empresa</label>
                                        <input name="company" type="text" class="form-control resume" id="empresa"
                                            placeholder="Ingresa el nombre de tu empresa" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese el nombre de su empresa
                                        </div>
                                    </div>
                                </div>
                                <div class="col-8">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Cargo</label>
                                        <input name="job" type="text" class="form-control resume" id="cargo"
                                            placeholder="Ingresa tu cargo" required>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese su cargo
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 ">
                                    <div class="form-group app-label">
                                        <label class="text-muted">Mensaje</label>
                                        <textarea name="comments" id="comments" rows="5" class="form-control resume"
                                            placeholder="Cuentanos como podemos ayudarte" required></textarea>
                                        <div class="invalid-feedback pl-2 pt-1">
                                            Ingrese un mensaje
                                        </div>
                                    </div>

                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <button class="submitBnt btn btn-primary" type="submit">Enviar Mensaje</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

【问题讨论】:

  • 尝试在浏览器开发工具中打开你的脚本并放置一些断点并跟随代码的执行。确保您的逻辑按照您的想法行事。

标签: javascript jquery ajax bootstrap-4


【解决方案1】:

由于浏览器正在发送表单,因此永远无法访问 ajax 部分。要发送 ajax,请阻止默认行为并仅在验证发生时执行 ajax 部分。

   'use strict';
   window.addEventListener('load', function () {
         // Fetch all the forms we want to apply custom Bootstrap validation styles to
         var forms = document.getElementsByClassName('needs-validation');
         // Loop over them and prevent submission
         var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
               //Prevent the browser default action
               event.preventDefault();
               event.stopPropagation();
               if (form.checkValidity()) {
                     try {
                        var data = {
                           firstname: form.name.value,
                           lastname: form.lastname.value,
                           company: form.company.value,
                           email: form.email.value,
                           phone: form.phone.value,
                           jobtitle: form.job.value,
                           message: form.comments.value,
                        }

                        $.ajax({
                           type: "POST",
                           url: url,
                           data: data
                        });
                     } catch (error) {
                        console.log(error)
                     }
               }
               form.classList.add('was-validated');
            }, false);
         });
   }, false);
})();```

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 2017-09-02
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多