看到我无法找到解决问题的方法,我可能会错误地解决这个问题。
我尝试使用AJAX构建表单,该表单将在提交表单时提供错误响应或成功响应。我能够收到发送到我的表单的错误响应,但它是在JSON中,这显然看起来很糟糕。目前我正在使用简化形式,只有两个要求:(1)名称必须是John和(2)日期必须是将来。
这是我的HTML:
<!DOCTYPE html>
<head>
<title>AJAX Form</title>
</head>
<body>
<form action="ajax/contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<input type="text" placeholder="" class="textinput" name="departuredate" id="departing">
</div>
<div>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<div id="ack"></div>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script>
$(document).ready(function() {
$("#departing").datepicker({
//minDate: 0,
//maxDate: "+1y",
dateFormat: "yy-mm-dd",
defaultDate: new Date(),
});
});
</script>
</body>
</html>
这是我的PHP文件:
<?php
$errors = array();
$form_data = array();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$date = htmlspecialchars($_POST['departuredate']);
$message = htmlspecialchars($_POST['message']);
if (date('Y-m-d') > $date) {
$errors['date'] = "Date is in the past";
goto end;
}
if ($name != 'John') {
$errors['name'] = "Name is not John";
goto end;
}
end:
if (empty($errors)) {
$form_data['success'] = true;
} else {
$form_data['errors'] = $errors;
}
echo json_encode($form_data);
?>
这是我的AJAX文件:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method');
$.ajax({
url: url,
type: type,
data: that.serialize(),
dataType: 'json',
cache: false,
success:
function(result) {
if(!result.success) {
$('#ack').html(JSON.stringify(result.errors));
console.log(result.errors);
} else {
console.log('Valid date and name entries');
}
}
});
return false;
});
谢谢!