我制作了一个包含 6 个不同 ID 的表单(contatcForm、emailForm、inquiryForm、CompForm 和 otherForm)的网页。所有表格都有 4 个字段(姓名、电子邮件、主题和消息)。现在的问题是:我无法找到合适的方式来使用 ajax 来验证和提交特定的表单。
我当前的脚本是:
/ 使用 $('html').on 是因为表单页面是通过 ajax 加载的/
$('html').on ('click','.sendit', function (){
Var a = $(this).parent ('form').attr ('id');
a.submit (submit);
});
function submit (){
Var form = $(this);
If (! $(.name).val () || ! $(.email).val () || ! $(.subject).val () || ! $(.message).val ()){
$('.incomp').show ();
} else {
$('.sending').show ();
$.ajax ({
url: form.attr ('action') + "?ajax=true",
type: form.attr ('method'),
data: form.serialize(),
success: finished
});
}
return false;
}
Function finished (response){
response = $.trim (response);
$('.sending').show ();
If (response == "success"){
$('.success').show ();
} else {
$('.error').show ();
}
}
该脚本可以很好地提交表单数据,但是使用它的缺点是:'.show ();' 以所有形式执行。
HTML 代码:
<ul><li>Contact</li>
<form id="contactForm" action="processForm.php" method="post">
<span class="sending"><p>Sending your message. Please wait...</p></span>
<span class="success"><p>Thanks for sending your message! We'll get back to you shortly.</p></span>
<span class="error"><p>There was a problem sending your message. Please try again.</p></span>
<span class="incomp"><p>Please complete all the fields in the form before sending.</p></span>
<input type="text" name="name" placeholder="name" />
<input type="email" name="email" placeholder="email" />
<input type="text" name="subject" placeholder="Subject" />
<textarea name="message" placeholder="Message"></textarea>
<input type="submit" class="sendit" name="sendMessage" value="Send Email" />
</form></li>
<li>Inquiry</li>
<form id="inquiryForm" action="processForm.php" method="post">
<span class="sending"><p>Sending your message. Please wait...</p></span>
<span class="success"><p>Thanks for sending your message! We'll get back to you shortly.</p></span>
<span class="error"><p>There was a problem sending your message. Please try again.</p></span>
<span class="incomp"><p>Please complete all the fields in the form before sending.</p></span>
<input type="text" name="name" placeholder="name" />
<input type="email" name="email" placeholder="email" />
<input type="text" name="subject" placeholder="Subject" />
<textarea name="message" placeholder="Message"></textarea>
<input type="submit" class="sendit" name="sendMessage" value="Send Email" />
</form>
</ul>
其他表单相同,但formID根据表单标题不同(#complaintForm,#otherForm)
感谢和问候