抱歉,可能对于更有经验的用户来说,这是一个基础问题,但我正在学习Ajax,这是一个陡峭的学习曲线,但我慢慢地接近目标。我有以下脚本,它可以完美地工作,除了客户端验证部分。我试图阻止表单在表单字段为空时被提交。然而,我的验证部分没有起作用(被忽略/跳过)。
如果有一位有 Ajax 经验的人能检查一下我的代码并可能提出建议,我将不胜感激。
如果有一位有 Ajax 经验的人能检查一下我的代码并可能提出建议,我将不胜感激。
<div id="depMsg"></div>
<form name="dep-form" action="deposit/submitReference.php" id="dep-form" method="post">
<span style="color:red">Submit Reference Nr:</span><br />
<input type="text" name="reference" value="" /><br />
<span id="reference-info"></span><br />
<input type="submit" value="Submit" name="deposit" class="buttono" />
</form>
</div>
$(function() {
var valid
//call validate function
valid = validateDep()
if(valid){
// Get the form.
var form = $('#dep-form');
// Get the messages div.
var formMessages = $('#depMsg');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
}
});
});
});
function validateDep() {
var valid = true;
if(!$("#reference").val()) {
$("#reference-info").html("(required)");
$("#reference").css('background-color','#FFFFDF');
valid = false;
}
return valid;
}
</script>