gpt4 book ai didi

javascript - 在哪里将我的 ajax 添加到 Bootstrap 4 的表单验证 javascript 中?

转载 作者:行者123 更新时间:2023-12-01 00:02:59 25 4
gpt4 key购买 nike

我对 javascript 真的很糟糕,但是正在学习。这是Bootstrap 4's form validation js :

( function() {
"use strict";

window.addEventListener( "load", function() {
var forms = document.getElementsByClassName( "needs-validation" );

var validation = Array.prototype.filter.call( forms, function( form ) {
form.addEventListener( "submit", function( event ) {
if ( form.checkValidity() === false ) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add( "was-validated" );
},
false );
});
},
false );
})();

在哪里添加 jQuery Ajax 内容?我是否将其添加到 Bootstrap js 中或创建一个全新的独立函数?

$.ajax({
url : "contact.php",
type : "POST",
dataType : "json",
data : $( this ).serialize(),
success : function( data )
{
if ( data.type == "error" ) {
output = '<div class="error">'+data.text+"</div>";
}
else {
$( form )[0].reset();
output = '<div class="success">'+data.text+"</div>";
}
$( "#contact-results" ).html( output );
}
});

最佳答案

这是一个simple tutorial关于如何将 JavaScript 添加到您的代码中。

现在您知道可以在哪里添加 javascript:您的 ajax 调用将在表单验证后被调用:

(function () {
"use strict";
window.addEventListener("load", function () {
var forms = document.getElementsByClassName("needs-validation");

var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener("submit", function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");

// Here you are going to add your ajax call after checking if the form validation is valid
if (form.checkValidity() === true) {
event.preventDefault();
// To reset the appearance of the form (for instance, in the case of dynamic form submissions using AJAX), remove the .was-validated class from the <form> again after submission. (boostrap doc)
form.classList.remove("was-validated");
$.ajax({
url: "contact.php",
type: "POST",
dataType: "json",
data: $(this).serialize(),
success: function (data) {
if (data.type == "error") {
output = '<div class="error">' + data.text + "</div>";
}
else {
$(form)[0].reset();
output = '<div class="success">' + data.text + "</div>";
}
$("#contact-results").html(output);
}
});
}

},
false);
});
},
false);
})();

关于javascript - 在哪里将我的 ajax 添加到 Bootstrap 4 的表单验证 javascript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60587789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com