我正在使用 AJAX 将远程页面加载到 Bootstrap 5 Modal 中
打开模式的代码:
<button type="button" data-id="5" class="btn btn-status">Open</button>
<div class="modal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" id="support_modal">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Support Ticket</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.btn-status').click(function () {
var custId = $(this).data('id');
$.ajax({
url: 'driver_support.php',
type: 'get',
data: { custId: custId },
success: function (response) {
$('.modal-body').html(response);
$('#support_modal').modal('show');
}
});
});
});
</script>
但是这按预期工作...
我在模式(driver_support.php)中加载的页面正在使用 formvalidation.io 来验证表单。
直接在浏览器中查看页面时,验证工作正常
当页面通过 AJAX 加载到模式中时,它不会验证表单。
控制台中没有错误。
页面中的代码加载到模式中(driver_support.php):
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Support Ticket</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="formvalidation/dist/css/formValidation.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.3/es6-shim.min.js"></script>
<script src="formvalidation/dist/js/FormValidation.min.js"></script>
<script src="formvalidation/dist/js/plugins/Bootstrap5.min.js"></script>
</head>
<body>
<form name="tickets" id="tickets" action="my_script.php" method="post">
<div class="mb-3">
<label class="form-label text-dark">Post a reply</label>
<textarea class="form-control" rows="3" name="message"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-primary">Reply</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', function (e) {
FormValidation.formValidation(document.getElementById('tickets'), {
fields: {
message: {
validators: {
notEmpty: {
message: 'Please enter a message'
}
}
},
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
submitButton: new FormValidation.plugins.SubmitButton(),
defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
bootstrap: new FormValidation.plugins.Bootstrap5({
rowSelector: '.mb-3',
}),
},
});
});
</script>
感谢您的宝贵时间。
问题是当您使用 AJAX 加载页面时,验证脚本在文档加载侦听器下执行:
document.addEventListener('DOMContentLoaded', function (e) {
//...
并且由于它共享相同的
document
,DOM 已经加载,因此它永远不会执行。
随着加载页面中的脚本同步加载,您可以简单地删除侦听器,并让代码在 JQ 将其添加到模态后立即运行:
// remove the listener
//document.addEventListener('DOMContentLoaded', function (e) {
FormValidation.formValidation(document.getElementById('tickets'), {