如何使用 AJAX 发布数据并使用bootstrap 5进行验证?

7cwmlq89  于 2023-01-15  发布在  Bootstrap
关注(0)|答案(2)|浏览(473)

我如何在bootstrap 5中发布 AJAX 表单验证?

// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
  'use strict'

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }
   
        form.classList.add('was-validated')
      }, false)
    })
})()

我有个大问题。有人能帮帮我吗?

fjaof16o

fjaof16o1#

引导文档提供的上述启动器代码使用JavaScript Constraint Validation APIcheckValidity()方法来验证表单。
HTMLinputElement.checkValidity()方法返回一个布尔值,该值指示元素值的有效性。如果该值无效,此方法也会在元素上触发无效事件。
如果验证成功,您可以发出 AJAX 请求,如下所示,

if (!form.checkValidity()) {
   event.preventDefault()
   event.stopPropagation()
}else{
   //make your ajax request here
}

下面是使用JavaScript Fetch API和FormData API AJAX 请求示例

if (!form.checkValidity()) {
   event.preventDefault()
   event.stopPropagation()
}else{
  try {
     const postData = new FormData(form)
     const response = await fetch('url', {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify(postData)
      });
     //Response from server
     const data = await response.json();
  }catch(e){
     //handle error
     console.log(e)
  }
}
9o685dep

9o685dep2#

(function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                } else {
                    event.preventDefault();  // event.default or form submit
                    formPost();  // call function whatever you want
                }
                form.classList.add('was-validated')
            }, false)
        })
})()

function formPost(){
    var form_data = $("form#mainform").serialize();

    $.ajax({
        url: "action.php",
        method: "POST",
        data: form_data,
        // dataType:"json",
        success: function (data) {
            $('#queryResulDiv').html(data);
            console.log(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#queryResulDiv').html("ERROR:" + xhr.responseText + " - " + thrownError);
        },
        complete: function () {

        }
    })
}

相关问题