我在 php 中创建了一个简单的注册表单并对用户输入进行了验证。我给每个$error[]
数组一个字符串索引。在示例中,它是这样的:$error['fn']
我这样做是因为我想使用 Ajax json 数据类型在用户输入旁边/下方显示每个验证错误。但由于某种原因,只有一个数组输出显示,而另一个输出则不显示。
它应该显示用户名输入下方的其他输出。如何显示其他输出以及我在哪里犯了错误?
<?php
require('../includes/config.php');
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (empty($_POST['fullname'])) {
$error['fn'] = "Please fill this field";
echo json_encode($error);
}
if (! $user->isValidFullname($fullname)){
$error['fn'] = 'Your name must be alphabetical characters';
echo json_encode($error);
}
}
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (empty($_POST['username'])) {
$error['un'] = "Please fill this field";
echo json_encode($error);
}
if (! $user->isValidUsername($username)){
$error['un'] = 'Your username must be at least 3 alphanumeric characters';
echo json_encode($error);
}
if (! $user->isUsernameAlreadyinUse($username)){
$error['un'] = 'This username already in use';
echo json_encode($error);
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("#register-form").on("submit", function(e) {
e.preventDefault();
var fullname = $("#fullname").val();
var username = $("#username").val();
$.ajax({
type: "POST",
url: "registercontrol.php",
data: {
fullname: fullname,
username: username
},
dataType: "json",
success: function(result) {
$("#vfullname").html(result['fn']);
$("#vusername").html(result['un']);
}
});
});
});
</script>
谢谢。
慕码人8056858