所以我有如下所示的index.php。
<head>
<script>
$(document).ready(function() {
$('#register').submit(function(event) {
var username = $("input[name='username']").val();
var email = $("input[name='email']").val();
var pwd1 = $("input[name='pwd1']").val();
var pwd2 = $("input[name='pwd2']").val();
$('.register-status').load('process.php',{
username: username,
email: email,
pwd1: pwd1,
pwd2: pwd2
});
event.preventDefault();
});
});
</script>
</head>
<body style="background-color:#a2a2a2" class="">
<div class="container col-3 bg-light mt-5 p-3 rounded">
<form id="register" action="process.php" method="post">
<div class="row d-flex justify-content-center">
<input class="border rounded m-2 text-center" type="text" name="username" placeholder="Username">
</div>
<div class="row d-flex justify-content-center">
<input class="border rounded m-2 text-center" type="text" name="email" placeholder="E-mail">
</div>
<div class="row d-flex justify-content-center">
<input class="border rounded m-2 text-center" type="text" name="pwd1" placeholder="Password">
</div>
<div class="row d-flex justify-content-center">
<input class="border rounded m-2 text-center" type="text" name="pwd2" placeholder="Confirm password">
</div>
<div class="row d-flex justify-content-center">
<button class="btn btn-warning mt-2" type="submit" name="register">Registration</button>
</div>
</form>
<p class="register-status"></p>
</div>
</body>
这是我的process.php
<?php
if (isset($_POST['register'])) {
if (empty($_POST['username'])) {
echo '<span>Please enter a username</span>';
}
if (empty($_POST['email'])) {
echo '<span>Please enter an E-mail</span>';
}
if (empty($_POST['pwd1'])) {
echo '<span>Please enter a password</span>';
}
if (empty($_POST['pwd2']) && !empty($_POST['pwd1'])) {
echo '<span>Please confirm your password</span>';
}
elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo '<span>Please enter a valid E-mail address</span>';
}
}
?>
我的问题是,我不刷新页面或不使用preventDefault()函数,不知道如何显示验证错误,因为如果不这样做,页面将重定向到process.php,所有验证错误都会显示出来那里。
您应该像这样在表单内部创建警报区域:
<div class="alert alert-danger" role="alert" style="display: none">
<!-- errors gonna be here -->
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
当您从后端部分收到错误时,应通过在jquery中切换该警报区域并将其填充后端响应错误来使此警报区域可见。>